一.创建流
通常通过数组或者集合方式创建
Arrays.stream(arr)
list.stream()
二.中间操作
map 映射
filter 过滤
distinct 去重
flatMap 扁平化(流中得到集合合并后,形成新的流)
sort 排序
peek 中间操作的forEach
skip/limit 舍弃/截取(不常用)
// 按重量升序排列
List<Apple> list1 = appleStore.stream().sorted(Comparator.comparing(Apple::getWeight, Comparator.
nullsLast(Comparator.naturalOrder()))).peek(System.out::print).collect(Collectors.toList());
// flatMap 遍历得到一个集合,合并后得到新的流,进行操作
List<List<Apple>> all = new ArrayList<>();
all.add(appleStore);
all.add(appleStore2);
List<Integer> ids = all.stream().flatMap(Collection::stream).map(Apple::getId).collect(Collectors.toList());
三.终止操作
匹配和查找
anyMatch 只要有一个匹配,返回true
allMatch 全部匹配,返回true
noneMatch 都不匹配,返回true
findFirst 返回第一个元素
findAny 返回任意元素
归约 reduce
//求list中的和,以0为基数
Integer reduce = integers.stream().reduce(0, (a, b) -> a + b);
//Integer的静态方法
int sum = integers.stream().reduce(0, Integer::sum);
————————————————
版权声明:本文为CSDN博主「爱思考的王同学」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_37967166/article/details/89153568
收集器
转list
转set
转map
字符串拼接
// list
List<String> list = appleStore.stream().map(Apple::getColor).collect(Collectors.toList());
System.out.println(list);
// set
Set<String> set = appleStore.stream().map(Apple::getColor).collect(Collectors.toSet());
System.out.println(set);
// map 遇到key相同,后者取代前者
Map<String, Apple> map = appleStore.stream()
.collect(Collectors.toMap(Apple::getColor, item -> item, (k1, k2) -> k2));
// 拼接成一个字符串
list.stream().collect(Collectors.joining("_"));
分组
groupingBy
// 苹果按颜色分类,并求平均重量
appleStore.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors
.averagingInt(value -> value.getWeight()))).forEach((k, v) -> {
System.out.println(k + ":" + v);
});