Java 8 Stream Api 中的 map和 flatMap 操作方法
1.前言
Java8提供了非常好用的StreamAPI,可以很方便的操作集合。今天我们来探讨两个Stream中间操作map(Functionmapper)和flatMap(Function>mapper)
2.map操作
map操作是将流中的元素进行再次加工形成一个新流。这在开发中很有用。比如我们有一个学生集合,我们需要从中提取学生的年龄以分析学生的年龄分布曲线。
放在Java8之前我们要通过新建一个集合然后通过遍历学生集合来消费元素中的年龄属性。现在我们通过很简单的流式操作就完成了这个需求。
示意图:
对应的伪代码:
//伪代码 Listages=studentList.stream().map(Student::getAge).collect(Collectors.toList());
3.flatMap操作
通过上面的例子,map操作应该非常好理解。那么flatMap是干嘛的呢?这样我们把上面的例子给改一下,如果是以班级为单位,提取所有班级下的所有学生的年龄以分析学生的年龄分布曲线。这时我们使用上面的方法还行得通吗?
List>studentGroup=gradeList.stream().map(Grade::getStudents).collect(Collectors.toList());
通过上面的一顿操作,我们只能得到每个班的学生集合的集合List>。我们还需要嵌套循环才能获取学生的年龄数据,十分不便。如果我们能返回全部学生的集合List
//flatMap提取Listmap提取年龄 List ages=grades.stream().flatMap(grade->grade.getStudents().stream()).map(Student::getAge).collect(Collectors.toList());
正如上面的伪代码所示,我们使用flatMap将所有的学生汇聚到一起。然后再使用map操作提取年龄。flatMap不同于map地方在于map只是提取属性放入流中,而flatMap先提取属性放入一个比较小的流,然后再将所有的流合并为一个流。有一种“聚沙成塔”的感觉。
再画一张图来加深理解:
4.总结
map操作和flatMap操作一旦你熟悉了,可以非常简便地解决一些数据流的操作问题。扩展一下知识,其实Java8中不光Stream中存在这两种操作,其实Optional
以上所述是小编给大家介绍的Java8StreamApi中的map和flatMap操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。