https://juejin.cn/post/6844903830254010381
Stream简介
Stream 是Java8 新增的API。
Stream将元素集合看作一种流, 流在管道中传输并执行筛选、 排序、聚合等操作最终获得我们想要的结果。
Stream可以极大提高生产力,让Java代码高效、干净、简洁。
一、创建Stream
1. Collection.stream()
Arrays.asList("北京", "上海", "深圳")
.stream()
.forEach(System.out :: println);
2. Stream.of()
Stream.of("北京", "上海", "深圳")
.forEach(System.out :: println);
3. Arrays.stream()
Arrays.stream(new String[]{"北京", "上海", "深圳"})
.forEach(System.out :: println);
System.out.println("------------");
String[] strArr = new String[]{"北京", "上海", "深圳"};
// 左闭右开
Arrays.stream(strArr, 0, 2)
.forEach(System.out :: println);
// 输出
北京
上海
深圳
------------
北京
上海
二、操作Stream
流的操作可以分为两种类型
1)中间操作:可以有多个,每次返回一个新的流,可进行链式操作。
2)终端操作:只能有一个,每次执行完,这个流也就用光了,无法执行下一个操作,因此只能放在最后。
Stream的所有方法
1.中间操作
filter()
map()
mapToInt()
mapToLong()
mapToDouble()
flatMap()
flatMapToInt()
flatMapToLong()
flatMapToDouble()
distinct()
sorted()
peek()
limit()
skip()
filter()
从流中筛选出我们想要的元素
map()
将一个流中的元素转化成新的流中的元素
mapToInt()
mapToLong()
mapToDouble()
flatMap()
flatMapToInt()
flatMapToLong()
flatMapToDouble()
distinct()
去重
sorted()
排序
peek()
limit()
skip()
2.终端操作
forEach()
forEachOrdered()
toArray()
reduce()
collect()
min()
max()
count()
anyMatch()
allMatch()
noneMatch()
findFirst()
findAny()