Stream

阶段

不调用终止方法,中间的操作不会执行
IntStream 常见方法

forEach(System.out::println)
forEachOrdered(System.out::println)
元素的收集collect()
1收集为Set: Collectors.toSet()
2收集为List: Collectors.toList()
3收集到任意的Collection类型: Collectors.toCollection(LindedList::new) 也可以使用如LinkedHashSet::new 和 PriorityQueue::new
4收集到Array: toArray(String[]::new)

5收集到Map: Collectors.toMap(Function.identity(), s-> (int) s.chars.distinct().count()) // key: t->t, value: 元素的不同的字母个数

6分组收集groupingBy

分组时,如果分组的字段中有值为null的时候,会抛Null Pointer Exception
解决方法: 使用Optional包裹一下
Collectors.groupingBy(x->Optional.ofNullable(x));
![]()
---
Examples:



Example: group by + mapping to set



groupby + reducing

多级分组

分区操作 Collectors.partitioningBy() 根据返回值是否为true,分为true列表,false列表

统计总数: Collectors.counting()
拼接: Collectors.joining()

---

聚合操作

reduce()


方法引用

其他:
anyMatch()
sum/average/sumaryStatistics()
最大/最小/总和/平均值
比较器 Comparator
Optional<T> min(Comparator<? super T> comparator)
比数值: Comparator.comparing(Integer::intValue)
// 错误用法
Stream.max(Integer::max)
Stream.min(Integer::mix)
当使用Integer.max(v, k), 如果数据中全部都是正数,则返回值总是正数
Stream.max()中,是以返回值的正负和0值来判断数据大小的

正确写法
![]()

比String: Comparator.comparing(String::valueOf)
对象类型Object: Comparator.comparing(User::getAge)
比日期: Comparrator.comparing(LocalDate::toEpochDay)
使用IntStream, LongStream, DoubleStream: IntSream.of(xx,xx).min()
sorted() 自然序排序
倒序: sorted(Comparator.reverseOrder())
sorted(Comparator.comparing(Student::getAge).reversed())
合并2个流: Stream.concat(xxStr1, xxStr2)
---
map ,
flatMap: 对流进行扁平化

本文详细介绍了Java 8的Stream API,包括中间操作、终结操作,如forEach、collect、groupBy、reduce等,并展示了如何进行集合转换、分组、聚合和排序。还探讨了错误的比较器使用方式及正确解决方案,以及如何进行流的合并和扁平化操作。
1621

被折叠的 条评论
为什么被折叠?



