JDK8都10岁了,你还在用for循环遍历list吗?

x33g5p2x  于2022-08-17 转载在 其他  
字(6.6k)|赞(0)|评价(0)|浏览(550)

简介

Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。

Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

熟悉Linux的同学对这种风格一定不陌生,因为它跟Linux的|管道符的思想如出一辙。上面这段话引用自runoob.com,但是其教学代码都是基于String列表进行演示,考虑到实际情况百分之80的时候都是对PO、VO进行处理,因此以下通过一个PO进行讲解。

对比起for循环操作list,最大的弊端就是代码太长太乱了,如果涉及3-4张表的操作,也就是涉及多个PO操作,那个括号简直就是俄罗斯套娃,写到最后真的自己都不知道在写什么

  1. +--------------------+       +------+   +------+   +---+   +-------+
  2. | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
  3. +--------------------+       +------+   +------+   +---+   +-------+

PO代码

  1. public class UserPo {
  2.     private String name;
  3.     private Double score;
  4.     
  5.     // 省略构造函数及getter、setter
  6. }

以下操作均以UserPo进行讲解

filter

filter:过滤,就是过滤器,符合条件的通过,不符合条件的过滤掉

  1. // 筛选出成绩不为空的学生人数
  2. count = list.stream().filter(-> null != p.getScore()).count();

map

map:映射,他将原集合映射成为新的集合,在VO、PO处理的过程中较常见。在本例子中,原集合就是PO集合,新集合可以自定义映射为成绩集合,同时也可以对新集合进行相关操作

  1. // 取出所有学生的成绩
  2. List<Double> scoreList = list.stream().map(-> p.getScore()).collect(Collectors.toList());
  3. // 将学生姓名集合串成字符串,用逗号分隔
  4. String nameString = list.stream().map(-> p.getName()).collect(Collectors.joining(","));

sorted

sorted:排序,可以根据指定的字段进行排序

  1. // 按学生成绩逆序排序 正序则不需要加.reversed()
  2. filterList = list.stream().filter(-> null != p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());

forEach

forEach:这个应该是最常用的,也就是为每一个元素进行自定义操作
除了forEach操作会改变原集合的数据,其他的操作均不会改变原集合,这点务必引起注意

  1. // 学生成绩太差了,及格率太低,给每个学生加10分,放个水
  2. // forEach
  3. filterList.stream().forEach(-> p.setScore(p.getScore() + 10));

collect

collect:聚合,可以用于GroudBy按指定字段分类,也可以用于返回列表或者拼凑字符串

  1. // 按成绩进行归集
  2. Map<Double, List<UserPo>> groupByScoreMap = list.stream().filter(-> null != p.getScore()).collect(Collectors.groupingBy(UserPo::getScore));
  3. for (Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()) {
  4.     System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
  5. }
  6. // 返回list
  7. List<Double> scoreList = list.stream().map(-> p.getScore()).collect(Collectors.toList());
  8. // 返回string用逗号分隔
  9. String nameString = list.stream().map(-> p.getName()).collect(Collectors.joining(","));

statistics

statistics:统计,可以统计中位数,平均值,最大最小值

  1. DoubleSummaryStatistics statistics = filterList.stream().mapToDouble(-> p.getScore()).summaryStatistics();
  2. System.out.println("列表中最大的数 : " + statistics.getMax());
  3. System.out.println("列表中最小的数 : " + statistics.getMin());
  4. System.out.println("所有数之和 : " + statistics.getSum());
  5. System.out.println("平均数 : " + statistics.getAverage());

parallelStream

parallelStream:并行流,可以利用多线程进行流的操作,提升效率。但是其不具备线程传播性,因此使用时需要充分评估是否需要用并行流操作

  1. // 并行流
  2. count = list.parallelStream().filter(-> null != p.getScore()).count();

完整代码

  1. package com.cmx.tcn.stream;
  2. /**
  3.  * @author: Cai MinXing
  4.  **/
  5. public class UserPo {
  6.     private String name;
  7.     private Double score;
  8.     public UserPo(String name, Double score) {
  9.         this.name = name;
  10.         this.score = score;
  11.     }
  12.     public String getName() {
  13.         return name;
  14.     }
  15.     public void setName(String name) {
  16.         this.name = name;
  17.     }
  18.     public Double getScore() {
  19.         return score;
  20.     }
  21.     public void setScore(Double score) {
  22.         this.score = score;
  23.     }
  24.     @Override
  25.     public String toString() {
  26.         return "UserPo{" +
  27.                 "name='" + name + '\'' +
  28.                 ", score=" + score +
  29.                 '}';
  30.     }
  31. }
  1. package com.cmx.tcn.stream;
  2. import java.util.ArrayList;
  3. import java.util.Comparator;
  4. import java.util.DoubleSummaryStatistics;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.stream.Collectors;
  8. /**
  9.  * @author: Cai MinXing
  10.  * @create: 2020-03-25 18:15
  11.  **/
  12. public class StreamTest {
  13. //    +--------------------+       +------+   +------+   +---+   +-------+
  14. //    | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
  15. //    +--------------------+       +------+   +------+   +---+   +-------+
  16.     public static void main(String args[]){
  17.         List<UserPo> list = new ArrayList<>();
  18.         list.add(new UserPo("小一", 10.d));
  19.         list.add(new UserPo("小五", 50.d));
  20.         list.add(new UserPo("小六", 60.d));
  21.         list.add(new UserPo("小6", 60.d));
  22.         list.add(new UserPo("小空", null));
  23.         list.add(new UserPo("小九", 90.d));
  24.         long count = 0;
  25.         List<UserPo> filterList = null;
  26.         // filter 过滤器的使用
  27.         // 筛选出成绩不为空的学生人数
  28.         count = list.stream().filter(-> null != p.getScore()).count();
  29.         System.out.println("参加考试的学生人数:" + count);
  30.         // collect
  31.         // 筛选出成绩不为空的学生集合
  32.         filterList = list.stream().filter(-> null != p.getScore()).collect(Collectors.toList());
  33.         System.out.println("参加考试的学生信息:");
  34.         filterList.stream().forEach(System.out::println);
  35.         // map 将集合映射为另外一个集合
  36.         // 取出所有学生的成绩
  37.         List<Double> scoreList = list.stream().map(-> p.getScore()).collect(Collectors.toList());
  38.         System.out.println("所有学生的成绩集合:" + scoreList);
  39.         // 将学生姓名集合串成字符串,用逗号分隔
  40.         String nameString = list.stream().map(-> p.getName()).collect(Collectors.joining(","));
  41.         System.out.println("所有学生的姓名字符串:" + nameString);
  42.         // sorted排序
  43.         // 按学生成绩逆序排序 正序则不需要加.reversed()
  44.         filterList = list.stream().filter(-> null != p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());
  45.         System.out.println("所有学生的成绩集合,逆序排序:");
  46.         filterList.stream().forEach(System.out::println);
  47.         System.out.println("按学生成绩归集:");
  48.         Map<Double, List<UserPo>> groupByScoreMap = list.stream().filter(-> null != p.getScore())
  49.                 .collect(Collectors.groupingBy(UserPo::getScore));
  50.         for (Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()) {
  51.             System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
  52.         }
  53.         // forEach
  54.         filterList.stream().forEach(-> p.setScore(p.getScore() + 10));
  55.         System.out.println("及格人数太少,给每个人加10分");
  56.         filterList.stream().forEach(System.out::println);
  57.         // count
  58.         count = filterList.stream().filter(-> p.getScore() >= 60).count();
  59.         System.out.println("最后及格人数" + count);
  60.         DoubleSummaryStatistics statistics = filterList.stream().mapToDouble(-> p.getScore()).summaryStatistics();
  61.         System.out.println("列表中最大的数 : " + statistics.getMax());
  62.         System.out.println("列表中最小的数 : " + statistics.getMin());
  63.         System.out.println("所有数之和 : " + statistics.getSum());
  64.         System.out.println("平均数 : " + statistics.getAverage());
  65.         // 并行流 使用
  66.         count = list.parallelStream().filter(-> null != p.getScore()).count();
  67.         System.out.println("并行流处理参加考试的学生人数:" + count);
  68.     }
  69. }

来源:bugpool.blog.csdn.net/article/details/105122681

推荐3个原创springboot+Vue项目,有完整视频讲解与文档和源码:

【dailyhub】【实战】带你从0搭建一个Springboot+elasticsearch+canal的完整项目
  • 视频讲解:https://www.bilibili.com/video/BV1Jq4y1w7Bc/
  • 完整开发文档:https://www.zhuawaba.com/post/124
  • 线上演示:https://www.zhuawaba.com/dailyhub
【VueAdmin】手把手教你开发SpringBoot+Jwt+Vue的前后端分离后台管理系统
  • 视频讲解:https://www.bilibili.com/video/BV1af4y1s7Wh/
  • 完整开发文档前端:https://www.zhuawaba.com/post/18
  • 完整开发文档后端:https://www.zhuawaba.com/post/19
  • 线上演示:https://www.markerhub.com/vueadmin/
【VueBlog】基于SpringBoot+Vue开发的前后端分离博客项目完整教学
  • 视频讲解:https://www.bilibili.com/video/BV1PQ4y1P7hZ
  • 完整开发文档:https://www.zhuawaba.com/post/17

关注我,学Java

相关文章