Stream在Java8中出现,将要处理的元素视作流。
流的种类
顺序流 | stream | 主线程按顺序对流执行操作。 |
并行流 | parallelStream | 内部以多线程并行执行的方式对流进行操作,需要流中的数据处理无顺序要求。 |
流的创建
xxx.stream(); |
Arrays.stream(xxx); |
Stream.of(1, 2, 3, 4, 5, 6); |
Stream.iterate(0, (x) -> x + 3).limit(4); |
Stream.generate(Math::random).limit(3); |
流的遍历
list.stream().forEach(System.out::println); |
流的匹配
匹配第一个 | list.stream().filter(x -> x > 6).findFirst(); |
匹配任意一个 | list.stream().filter(x -> x > 6).findAny(); |
是否包含符合特定条件的元素,结果为布尔值 | list.stream().anyMatch(x -> x < 6); |
计算符合条件的总个数 | long count = list.stream().filter(x -> x > 6).count(); |
流的筛选
stream.filter(x -> x > 7).forEach(System.out::println); |
流的映射
以函数作为参数,将每个元素映射成新的 | list.stream().map(x -> x + 3).collect(Collectors.toList()) |
流的归约
list.stream().reduce((x, y) -> x + y); |
流的收集
流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。
归集
list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); |
list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); |
list.stream().collect(Collectors.toMap(ABC::getA, ABC::getB, (x, y) -> x)) 第一个参数:key 第二个参数:value 第三个方式:如果待加入的key与现有key产生冲突,如何处理 |
统计
- 计数:count
- 平均值:averagingInt、averagingLong、averagingDouble
- 最值:maxBy、minBy
- 求和:summingInt、summingLong、summingDouble
- 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
list.stream().collect(Collectors.averagingDouble(ABC::getA)); |
list.stream().map(ABC::getA).collect(Collectors.maxBy(Integer::compare)); |
分组
partitioningBy | list.stream().collect(Collectors.partitioningBy(x -> x.getA() > 8000)); —— A |
groupingBy | list.stream().collect(Collectors.groupingBy(Person::getSex)); —— B |
list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); —— C |
A
员工按薪资是否大于8000分组情况: {false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]} |
B
员工按性别分组情况: {female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]} |
C
员工按性别、地区: {female={New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Person@16b98e56]}, male={New York=[mutest.Person@27d6c5e0, mutest.Person@15aeb7ab], Washington=[mutest.Person@2d98a335]}} |
联结
list.stream().map(p -> p.getName()).collect(Collectors.joining(",")); |
排序
list.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName) .collect(Collectors.toList()); |
// 自定义排序 list.stream().sorted((p1, p2) -> { |
提取
合并与去重 | Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); |
限制数量 | Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList()); |
跳过前n个 | Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); |