java 8 stream API<一>

本文深入探讨Java Stream API的高效使用方法,包括流的短路运算特性、flatMap的元素合并技巧、以及如何通过分组和分区实现数据的高级聚合。通过具体的代码示例,读者将学会如何利用Stream API简化数据处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.流不是对所有的元素都进行第一次操作接着进行第二次操作,而是对于一个元素执行完所有操作,所有操作都具有短路运算 跟java && || 运算符一致

伪代码: 

list.stream().mapToInt(item -> {int lengt = item.length();System.out.println(item);

return length;}).filter(length -> length == 5).findFirst().isPresent(System.out : println)

二.flatMap 将多个stream的多个元素里合并成一个stream   

伪代码:

list.stream().map(item -> item.spilt(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList())复制代码

伪代码:

List<String> reuslt = list.stream().flatMap.flatMap(item->list2.stream().map(item2->item+""+item2)).collect(collectors.toList());复制代码

三.分组和分区

申明一个student类,stream可以使用Collectors.groupingBy(Student::getName))来根据学生姓名分组,类似与sql语句的group by

分组:

Map<String,List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));

Map<Integer,List<Student>>map = students.stream().collect(Collectors.groupingBy(Student::getScore));Map<String,Long>map = student.stream().collect(Collectors.groupingBy(Student::getName,Collectors.counting());

Map<String,Double>map = students.stream().collect(Collectors.groupingBy(Student::getName,Collectors.averagingDouble(Student::getScore)));

多级分组:

Map<Integer,Map<String,List<Student>>> map = students.Stream().collect(groupingBy(Student::getScore,groupinBy(Student::getName)))


分区:

Map<Boolean,List<Student>> map = students.stream().collect(Collectors.partitioningBy(student->student.getScore()>=90));

多级分区:

Map<Boolean,Map<Boolean,List<Student>>> map = students.stream().collect(partitioningBy(student -> student.getScore()>80,partitionBy(student -> student.getScore()>90)));复制代码

jdk 实现的方式越具体越好,比如由student创建的集合的长度计算可以直接用 .size()方法得出,但是jdk提供了许多实现的方法,其中方法越具体其扩展性越高,比如我可以得到student创建的集合里去重人名的集合长度



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值