前言
Java 8 (又称为 jdk 1.8) 是 Java 语言开发的一个主要版本。 Oracle 公司于 2014 年 3 月 18 日发布 Java 8 ,它支持函数式编程,新的 JavaScript 引擎,新的日期 API,新的Stream API 等。 新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中。它可以让你以一种声明的方式处理数据,从而写出高效率、干净、简洁的代码。 这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
一、Stream 特性
- 元素是特定类型的对象,形成一个队列。 Java中的Stream不会存储元素,而是按需计算按照特定的规则对数据进行计算,一般会输出结果。
- Stream不会改变数据源,一般情况下会产生一个新的集合或者新值。
- Stream流的来源,可以是集合,数组,I/O channel, 产生器generator 等等。
- Stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。
- 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。
Stream流的操作可以大概分为2种:
1、中间操作:每次操作都返回流对象本身。
2、终端操作:一个流只可以进行一次终端操作,即产生一个新的集合或者新值。终端操作结束后流无法再次使用。
二、Stream 创建
在 Java 8 中, Stream可以由集合或数组创建而来,生成的流有2种类型: 1、stream() :串行流,由主线程按顺序对流执行操作。 2、parallelStream() :并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。例如计算集合中的数量之和。如果流种数据量很大,并行流可以加快处理速度。串行流可以通过parallel()方法把顺序流转换成并行流。
2.1 用集合创建流
因为集合继承或实现了java.util.Collection接口,而Collection接口定义了stream()和parallelStream()方法,所以可通过集合的stream() 和parallelStream()方法创建流。
1. // 创建集合2. List<String> list = Arrays.asList("张三", "李四", "王五");3. // 创建一个串行流4. Stream<String> stream = list.stream();5. // 创建一个并行流6. Stream<String> parallelStream = list.parallelStream();
2.2 用数组创建流
使用java.util.Arrays.stream(T[] array)方法用数组创建流。
1. // 创建数组2. String[] persons = {"张三", "李四", "王五"};3. // 创建一个串行流4. Stream<String> stream = Arrays.stream(persons);5. // 创建一个并行流6. Stream<String> parallelStream = Arrays.stream(persons).parallel();
2.3 Stream静态方法
使用Stream的静态方法生成Stream,例如of()、iterate()、generate()等。
1. Stream<String> stream2 = Stream.of("张三", "李四", "王五");2.3. // 输出5个奇数 1 3 5 7 94. Stream<Integer> stream3 = Stream.iterate(1, x -> x + 2).limit(5);5. stream3.forEach(System.out::println);6.7. // 生成2个UUID8. Stream<UUID> stream4 = Stream.generate(UUID::randomUUID).limit(2);9. stream4.forEach(System.out::println);
三、Stream 使用案例
数据准备,学生数据,学生类,以及测试数据
1. /**2. * @Description 学生类3. * @Author Mr.nobody4. * @Date 2021/1/175. * @Version 1.06. */7. public class Student {8. // 主键9. private String id;10. // 姓名11. private String name;12. // 年龄13. private int age;14. // 性别15. private String sex;16. // 成绩17. private double score;18.19. public Student(String id, String name, int age, String sex, double score) {20. this.id = id;21. this.name = name;22. this.age = age;23. this.sex = sex;24. this.score = score;25. }26. // 省略get和set方法,toString方法,如若测试需自行添加27. }28.29. List<Student> students = new ArrayList<>(16);30. students.add(new Student("1", "张三", 18, "male", 88));31. students.add(new Student("2", "李四", 17, "male", 60));32. students.add(new Student("3", "王五", 18, "male", 100));33. students.add(new Student("4", "赵六", 20, "male", 10));34. students.add(new Student("5", "董七", 14, "female", 95));35. students.add(new Student("6", "幺八", 21, "male", 55));36. students.add(new Student("7", "老九", 20, "female", 66));37. students.add(new Student("8", "小明", 18, "male", 100));38. students.add(new Student("9", "小红", 22, "female", 95));39. students.add(new Student("10", "小张", 25, "male", 90));
3.1 遍历 forEach
1. students.stream().forEach(System.out::println);2.3. // 输出结果4. Student{id='1', name='张三', age=18, sex=male, score=88.0}5. Student{id='2', name='李四', age=17, sex=male, score=60.0}6. Student{id='3', name='王五', age=18, sex=male, score=100.0}7. Student{id='4', name='赵六', age=20, sex=male, score=10.0}8. Student{id='5', name='董七', age=14, sex=female, score=95.0}9. Student{id='6', name='幺八', age=21, sex=male, score=55.0}10. Student{id='7', name='老九', age=20, sex=female, score=66.0}11. Student{id='8', name='小明', age=18, sex=male, score=100.0}12. Student{id='9', name='小红', age=22, sex=female, score=95.0}13. Student{id='10', name='小张', age=25, sex=male, score=90.0}
3.2 过滤 filter
1. // 过滤出成绩100分的学生2. List<Student> students1 =3. students.stream().filter(student -> student.getScore() == 100).collect(Collectors.toList());4. students1.forEach(System.out::println);5.6. // 输出结果7. Student{id='3', name='王五', age=18, sex=male, score=100.0}8. Student{id='8', name='小明', age=18, sex=male, score=100.0}
3.3 查找 findFirst,findAny
一般filter和find搭配使用,即从过滤符合条件的数据中,获得一个数据。
1. // 串行流,匹配第一个2. Optional<Student> studentOptional =3. students.stream().filter(student -> student.getAge() >= 20).findFirst();4. if (studentOptional.isPresent()) {5. Student student = studentOptional.get();6. System.out.println(student);7. }8. // 上面输出语句可简写如下9. // studentOptional.ifPresent(System.out::println);10.11. // 并行流,匹配任意一个,findAny一般用于并行流12. Optional<Student> studentOptiona2 =13. students.parallelStream().filter(student -> student.getAge() >= 20).findAny();14. studentOptiona2.ifPresent(System.out::println);15.16. // 输出结果17. Student{id='4', name='赵六', age=20, sex=male, score=10.0}18. Student{id='7', name='老九', age=20, sex=female, score=66.0}
3.4 匹配 match
1. // 是否存在100分的学生2. boolean anyMatch = students.stream().anyMatch(student -> student.getScore() == 100);3. // 是否全部学生都100分4. boolean allMatch = students.stream().allMatch(student -> student.getScore() == 100);5. // 是否全部学生都没有100分6. boolean noneMatch = students.stream().noneMatch(student -> student.getScore() == 100);7. System.out.println(anyMatch);8. System.out.println(allMatch);9. System.out.println(noneMatch);10.11. // 输出结果12. true13. false14. false
3.5 映射 map
映射,顾名思义,将一个对象映射成另外一个对象。即一个Stream流中的所有元素按照一定的映射规则,映射到另一个流中。映射有map和flatMap两种类型: 1、map:接收一个函数作为参数,此函数作用到Stream中每一个元素,形成一个新的元素,所有新的元素组成一个新的流。 2、flatMap:接收一个函数作为参数,它将流中的每个元素都转换成另一个流,然后把所有流再连接形成一个最终流。
1. // 获取每个学生的姓名2. List<String> studentNames =3. students.stream().map(Student::getName).collect(Collectors.toList());4. System.out.println(studentNames);5. // 每个学生的成绩加10分6. List<Double> studentScores = students.stream().map(student -> student.getScore() + 10)7. .collect(Collectors.toList());8. System.out.println(studentScores);9.10. // 输出结果11. [张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张]12. [98.0, 70.0, 110.0, 20.0, 105.0, 65.0, 76.0, 110.0, 105.0, 100.0]
1. List<String> list = Arrays.asList("a-b-c-d", "g-h-i");2. List<String> list1 = list.stream().flatMap(s -> Arrays.stream(s.split("-"))).collect(Collectors.toList());3. System.out.println(list1);4.5. // 输出结果6. [a, b, c, d, g, h, i]
3.6 截取流 limit
1. // limit方法用于获取指定数量的流。例如下面演示取出学习成绩大于70的5个人2. List<Student> students2 = students.stream().filter(student -> student.getScore() > 70)3. .limit(5).collect(Collectors.toList());4. students2.forEach(System.out::println);5. // 跳过第一个再取2个6. List<Student> students8 = students.stream().skip(1).limit(2).collect(Collectors.toList());7. // 获取5个int随机数,按从小到大排序8. Random random = new Random();9. random.ints().limit(5).sorted().forEach(System.out::println);10.11. // 输出结果12. Student{id='1', name='张三', age=18, sex=male, score=88.0}13. Student{id='3', name='王五', age=18, sex=male, score=100.0}14. Student{id='5', name='董七', age=14, sex=female, score=95.0}15. Student{id='8', name='小明', age=18, sex=male, score=100.0}16. Student{id='9', name='小红', age=22, sex=female, score=95.0}17. -149020271418. 14534054719. 36833215520. 38839939821. 1099579920
3.7 排序 sorted
sorted 方法用于对流中的元素进行排序,有两种排序: sorted():自然排序,流中元素需要实现Comparable接口。 sorted(Comparator<? super T> comparator):需要自定义排序器。
1. // 按成绩升序2. List<Student> students3 = students.stream().sorted(Comparator.comparing(Student::getScore))3. .collect(Collectors.toList());4. System.out.println("按成绩升序");5. students3.forEach(System.out::println);6. // 按成绩降序7. List<Student> students4 =8. students.stream().sorted(Comparator.comparing(Student::getScore).reversed())9. .collect(Collectors.toList());10. System.out.println("按成绩降序");11. students4.forEach(System.out::println);12. // 按成绩升序,再按年龄升序13. List<Student> students5 = students.stream()14. .sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getAge))15. .collect(Collectors.toList());16. System.out.println("按成绩升序,再按年龄升序");17. students5.forEach(System.out::println);18. // 按成绩升序,再按年龄降序19. List<Student> students6 = students.stream().sorted((s1, s2) -> {20. if (s1.getScore() != s2.getScore()) {21. return (int) (s1.getScore() - s2.getScore());22. } else {23. return (s2.getAge() - s1.getAge());24. }25. }).collect(Collectors.toList());26. System.out.println("按成绩升序,再按年龄降序");27. students6.forEach(System.out::println);
3.8 去重 distinct
1. List<String> list2 = Arrays.asList("a", "b", "a", "c", "f", "e", "f");2. List<String> list3 = list2.stream().distinct().collect(Collectors.toList());3. Set<String> stringSet = list2.stream().collect(Collectors.toSet()); // list转set也可以达到去重效果4. System.out.println(list3);5. System.out.println(stringSet);6.7. // 输出结果8. [a, b, c, f, e]9. [a, b, c, e, f]
3.9 统计 summaryStatistics
一些收集器能产生统计结果,例如Collectors提供了一系列用于数据统计的静态方法,它们主要用于int、double、long等基本类型上。
1. // 总和统计summaryStatistics2. DoubleSummaryStatistics doubleSummaryStatistics =3. students.stream().mapToDouble(Student::getScore).summaryStatistics();4. System.out.println("平均值:" + doubleSummaryStatistics.getAverage());5. System.out.println("总个数:" + doubleSummaryStatistics.getCount());6. System.out.println("最大值:" + doubleSummaryStatistics.getMax());7. System.out.println("最小值:" + doubleSummaryStatistics.getMin());8. System.out.println("总和值:" + doubleSummaryStatistics.getSum());9.10. // 输出结果11. 平均值:75.912. 总个数:1013. 最大值:100.014. 最小值:10.015. 总和值:759.0
1. // 统计个数2. long count = students.stream().count();3. // 平均值4. Double averageScore =5. students.stream().collect(Collectors.averagingDouble(Student::getScore));6. // 最大值和最小值7. Optional<Double> maxScore = students.stream().map(Student::getScore).max(Double::compare);8. Optional<Double> minScore = students.stream().map(Student::getScore).min(Double::compare);9. // 求和10. double sumScore = students.stream().mapToDouble(Student::getScore).sum();11. // 一次性统计所有12. DoubleSummaryStatistics doubleSummaryStatistics1 =13. students.stream().collect(Collectors.summarizingDouble(Student::getScore));14. System.out.println("单个维度计算:");15. System.out.println("统计个数:" + count);16. System.out.println("平均值:" + averageScore);17. maxScore.ifPresent(aDouble -> System.out.println("最大值:" + aDouble));18. minScore.ifPresent(aDouble -> System.out.println("最小值:" + aDouble));19. System.out.println("求和:" + sumScore);20. System.out.println("一次性统计所有:" + doubleSummaryStatistics1);21.22. // 输出结果23. 单个维度计算:24. 统计个数:1025. 平均值:75.926. 最大值:100.027. 最小值:10.028. 求和:759.0
3.10 归约 reduce
归约,把一个流归约(缩减)成一个值,能实现对集合求和、求乘积和求最值等操作。
1. List<Integer> integerList = Arrays.asList(6, 7, 1, 10, 11, 7, 13, 20);2. // 求和3. Optional<Integer> sum1 = integerList.stream().reduce(Integer::sum);4. // 求和,基于10的基础上5. Integer sum2 = integerList.stream().reduce(10, Integer::sum);6. // 求最大值7. Optional<Integer> max1 = integerList.stream().reduce((x, y) -> x > y ? x : y);8. // 求最大值,基于与50比较的基础上9. Integer max2 = integerList.stream().reduce(50, Integer::max);10. Optional<Integer> min = integerList.stream().reduce(Integer::min);11. // 求乘积12. Optional<Integer> product = integerList.stream().reduce((x, y) -> x * y);13. System.out.println("原始集合:" + integerList);14. System.out.println("集合求和:" + sum1.get() + "," + sum2);15. System.out.println("集合求最大值:" + max1.get() + "," + max2);16. System.out.println("集合求最小值:" + min.get());17. System.out.println("集合求积:" + product.get());18.19. // 输出结果20. 原始集合:[6, 7, 1, 10, 11, 7, 13, 20]21. 集合求和:75,8522. 集合求最大值:20,5023. 集合求最小值:124. 集合求积:8408400
3.11 归集 toList,toSet,toMap
Java中的Stream不会存储元素,而是按需计算按照特定的规则对数据进行计算,一般会输出结果。所以流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。比较常用的是toList、toSet和toMap,以及复杂的toCollection、toConcurrentMap等。
1. // 获取学生名字,形成新的list集合2. List<String> studentNames1 =3. students.stream().map(Student::getName).collect(Collectors.toList());4. // 获取年龄大于等于15的年龄set集合5. Set<Integer> ageSet = students.stream().filter(student -> student.getAge() >= 15)6. .map(Student::getAge).collect(Collectors.toSet());7. // 创建学生ID和学生实体的map8. Map<String, Student> studentMap =9. students.stream().collect(Collectors.toMap(Student::getId, student -> student));10. System.out.println(studentNames1);11. System.out.println(ageSet);12. studentMap.forEach((key, value) -> System.out.println(key + ":" + value));13.14. // 输出结果15. [张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张]16. [17, 18, 20, 21, 22, 25]17. 1:Student{id='1', name='张三', age=18, sex=male, score=88.0}18. 2:Student{id='2', name='李四', age=17, sex=male, score=60.0}19. 3:Student{id='3', name='王五', age=18, sex=male, score=100.0}20. 4:Student{id='4', name='赵六', age=20, sex=male, score=10.0}21. 5:Student{id='5', name='董七', age=14, sex=female, score=95.0}22. 6:Student{id='6', name='幺八', age=21, sex=male, score=55.0}23. 7:Student{id='7', name='老九', age=20, sex=female, score=66.0}24. 8:Student{id='8', name='小明', age=18, sex=male, score=100.0}25. 9:Student{id='9', name='小红', age=22, sex=female, score=95.0}26. 10:Student{id='10', name='小张', age=25, sex=male, score=90.0}
3.12 分组 partitioningBy,groupingBy
partitioningBy(分区):stream中的元素按条件被分为两个Map。 groupingBy(分组):stream中的元素按条件被分为多个Map。
1. // 按条件学生成绩是否大于等于60,划分为2个组2. Map<Boolean, List<Student>> studentScorePart = students.stream()3. .collect(Collectors.partitioningBy(student -> student.getScore() >= 60));4. // 按性别分组5. Map<String, List<Student>> studentSexMap =6. students.stream().collect(Collectors.groupingBy(Student::getSex));7. // 按年龄分组8. Map<Integer, List<Student>> studentAgeMap =9. students.stream().collect(Collectors.groupingBy(Student::getAge));10. // 先按性别分组,再按年龄分组11. Map<String, Map<Integer, List<Student>>> collect = students.stream().collect(12. Collectors.groupingBy(Student::getSex, Collectors.groupingBy(Student::getAge)));13. System.out.println("按条件学生成绩是否大于等于60,划分为2个组:");14. studentScorePart.forEach((aBoolean, students7) -> {15. System.out.println("成绩大于等于60?:" + aBoolean);16. students7.forEach(System.out::println);17. });18. System.out.println("按性别分组:");19. studentSexMap.forEach((sex, students7) -> {20. System.out.println("性别?:" + sex);21. students7.forEach(System.out::println);22. });23. System.out.println("按年龄分组:");24. studentAgeMap.forEach((age, students7) -> {25. System.out.println("年龄:" + age);26. students7.forEach(System.out::println);27. });28. System.out.println("先按性别分组,再按年龄分组:");29. collect.forEach((sex, integerListMap) -> {30. System.out.println("性别:" + sex);31. integerListMap.forEach((age, students7) -> {32. System.out.println("年龄:" + age);33. students7.forEach(System.out::println);34. });35. });36.37. //输出结果38. 按条件学生成绩是否大于等于60,划分为2个组:39. 成绩大于等于60?:false40. Student{id='4', name='赵六', age=20, sex=male, score=10.0}41. Student{id='6', name='幺八', age=21, sex=male, score=55.0}42. 成绩大于等于60?:true43. Student{id='1', name='张三', age=18, sex=male, score=88.0}44. Student{id='2', name='李四', age=17, sex=male, score=60.0}45. Student{id='3', name='王五', age=18, sex=male, score=100.0}46. Student{id='5', name='董七', age=14, sex=female, score=95.0}47. Student{id='7', name='老九', age=20, sex=female, score=66.0}48. Student{id='8', name='小明', age=18, sex=male, score=100.0}49. Student{id='9', name='小红', age=22, sex=female, score=95.0}50. Student{id='10', name='小张', age=25, sex=male, score=90.0}51. 按性别分组:52. 性别?:female53. Student{id='5', name='董七', age=14, sex=female, score=95.0}54. Student{id='7', name='老九', age=20, sex=female, score=66.0}55. Student{id='9', name='小红', age=22, sex=female, score=95.0}56. 性别?:male57. Student{id='1', name='张三', age=18, sex=male, score=88.0}58. Student{id='2', name='李四', age=17, sex=male, score=60.0}59. Student{id='3', name='王五', age=18, sex=male, score=100.0}60. Student{id='4', name='赵六', age=20, sex=male, score=10.0}61. Student{id='6', name='幺八', age=21, sex=male, score=55.0}62. Student{id='8', name='小明', age=18, sex=male, score=100.0}63. Student{id='10', name='小张', age=25, sex=male, score=90.0}64. 按年龄分组:65. 年龄:1766. Student{id='2', name='李四', age=17, sex=male, score=60.0}67. 年龄:1868. Student{id='1', name='张三', age=18, sex=male, score=88.0}69. Student{id='3', name='王五', age=18, sex=male, score=100.0}70. Student{id='8', name='小明', age=18, sex=male, score=100.0}71. 年龄:2072. Student{id='4', name='赵六', age=20, sex=male, score=10.0}73. Student{id='7', name='老九', age=20, sex=female, score=66.0}74. 年龄:2175. Student{id='6', name='幺八', age=21, sex=male, score=55.0}76. 年龄:2277. Student{id='9', name='小红', age=22, sex=female, score=95.0}78. 年龄:2579. Student{id='10', name='小张', age=25, sex=male, score=90.0}80. 年龄:1481. Student{id='5', name='董七', age=14, sex=female, score=95.0}82. 先按性别分组,再按年龄分组:83. 性别:female84. 年龄:2085. Student{id='7', name='老九', age=20, sex=female, score=66.0}86. 年龄:2287. Student{id='9', name='小红', age=22, sex=female, score=95.0}88. 年龄:1489. Student{id='5', name='董七', age=14, sex=female, score=95.0}90. 性别:male91. 年龄:1792. Student{id='2', name='李四', age=17, sex=male, score=60.0}93. 年龄:1894. Student{id='1', name='张三', age=18, sex=male, score=88.0}95. Student{id='3', name='王五', age=18, sex=male, score=100.0}96. Student{id='8', name='小明', age=18, sex=male, score=100.0}97. 年龄:2098. Student{id='4', name='赵六', age=20, sex=male, score=10.0}99. 年龄:21100. Student{id='6', name='幺八', age=21, sex=male, score=55.0}101. 年龄:25102. Student{id='10', name='小张', age=25, sex=male, score=90.0}
3.13 合并 joining
将stream中的元素用指定的连接符(没有的话,则直接连接)连接成一个字符串。
1. String joinName = students.stream().map(Student::getName).collect(Collectors.joining(", "));2. System.out.println(joinName);3.4. // 输出结果5. 张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张
四、演示代码获取
此演示代码程序已放到Github:https://github.com/LucioChn/java8-stream-demo
欢迎Star,给个支持!
作者:Μr.ηobοdy 链接:https://blog.csdn.net/chenlixiao007/article/details/112752413 来源:CSDN
