前言

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. 1. // 创建集合
  2. 2. List<String> list = Arrays.asList("张三", "李四", "王五");
  3. 3. // 创建一个串行流
  4. 4. Stream<String> stream = list.stream();
  5. 5. // 创建一个并行流
  6. 6. Stream<String> parallelStream = list.parallelStream();

2.2 用数组创建流

使用java.util.Arrays.stream(T[] array)方法用数组创建流。

  1. 1. // 创建数组
  2. 2. String[] persons = {"张三", "李四", "王五"};
  3. 3. // 创建一个串行流
  4. 4. Stream<String> stream = Arrays.stream(persons);
  5. 5. // 创建一个并行流
  6. 6. Stream<String> parallelStream = Arrays.stream(persons).parallel();

2.3 Stream静态方法

使用Stream的静态方法生成Stream,例如of()、iterate()、generate()等。

  1. 1. Stream<String> stream2 = Stream.of("张三", "李四", "王五");
  2. 2.
  3. 3. // 输出5个奇数 1 3 5 7 9
  4. 4. Stream<Integer> stream3 = Stream.iterate(1, x -> x + 2).limit(5);
  5. 5. stream3.forEach(System.out::println);
  6. 6.
  7. 7. // 生成2个UUID
  8. 8. Stream<UUID> stream4 = Stream.generate(UUID::randomUUID).limit(2);
  9. 9. stream4.forEach(System.out::println);

三、Stream 使用案例

数据准备,学生数据,学生类,以及测试数据

  1. 1. /**
  2. 2. * @Description 学生类
  3. 3. * @Author Mr.nobody
  4. 4. * @Date 2021/1/17
  5. 5. * @Version 1.0
  6. 6. */
  7. 7. public class Student {
  8. 8. // 主键
  9. 9. private String id;
  10. 10. // 姓名
  11. 11. private String name;
  12. 12. // 年龄
  13. 13. private int age;
  14. 14. // 性别
  15. 15. private String sex;
  16. 16. // 成绩
  17. 17. private double score;
  18. 18.
  19. 19. public Student(String id, String name, int age, String sex, double score) {
  20. 20. this.id = id;
  21. 21. this.name = name;
  22. 22. this.age = age;
  23. 23. this.sex = sex;
  24. 24. this.score = score;
  25. 25. }
  26. 26. // 省略get和set方法,toString方法,如若测试需自行添加
  27. 27. }
  28. 28.
  29. 29. List<Student> students = new ArrayList<>(16);
  30. 30. students.add(new Student("1", "张三", 18, "male", 88));
  31. 31. students.add(new Student("2", "李四", 17, "male", 60));
  32. 32. students.add(new Student("3", "王五", 18, "male", 100));
  33. 33. students.add(new Student("4", "赵六", 20, "male", 10));
  34. 34. students.add(new Student("5", "董七", 14, "female", 95));
  35. 35. students.add(new Student("6", "幺八", 21, "male", 55));
  36. 36. students.add(new Student("7", "老九", 20, "female", 66));
  37. 37. students.add(new Student("8", "小明", 18, "male", 100));
  38. 38. students.add(new Student("9", "小红", 22, "female", 95));
  39. 39. students.add(new Student("10", "小张", 25, "male", 90));

3.1 遍历 forEach

  1. 1. students.stream().forEach(System.out::println);
  2. 2.
  3. 3. // 输出结果
  4. 4. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  5. 5. Student{id='2', name='李四', age=17, sex=male, score=60.0}
  6. 6. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  7. 7. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  8. 8. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  9. 9. Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  10. 10. Student{id='7', name='老九', age=20, sex=female, score=66.0}
  11. 11. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  12. 12. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  13. 13. Student{id='10', name='小张', age=25, sex=male, score=90.0}

3.2 过滤 filter

  1. 1. // 过滤出成绩100分的学生
  2. 2. List<Student> students1 =
  3. 3. students.stream().filter(student -> student.getScore() == 100).collect(Collectors.toList());
  4. 4. students1.forEach(System.out::println);
  5. 5.
  6. 6. // 输出结果
  7. 7. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  8. 8. Student{id='8', name='小明', age=18, sex=male, score=100.0}

3.3 查找 findFirst,findAny

一般filter和find搭配使用,即从过滤符合条件的数据中,获得一个数据。

  1. 1. // 串行流,匹配第一个
  2. 2. Optional<Student> studentOptional =
  3. 3. students.stream().filter(student -> student.getAge() >= 20).findFirst();
  4. 4. if (studentOptional.isPresent()) {
  5. 5. Student student = studentOptional.get();
  6. 6. System.out.println(student);
  7. 7. }
  8. 8. // 上面输出语句可简写如下
  9. 9. // studentOptional.ifPresent(System.out::println);
  10. 10.
  11. 11. // 并行流,匹配任意一个,findAny一般用于并行流
  12. 12. Optional<Student> studentOptiona2 =
  13. 13. students.parallelStream().filter(student -> student.getAge() >= 20).findAny();
  14. 14. studentOptiona2.ifPresent(System.out::println);
  15. 15.
  16. 16. // 输出结果
  17. 17. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  18. 18. Student{id='7', name='老九', age=20, sex=female, score=66.0}

3.4 匹配 match

  1. 1. // 是否存在100分的学生
  2. 2. boolean anyMatch = students.stream().anyMatch(student -> student.getScore() == 100);
  3. 3. // 是否全部学生都100分
  4. 4. boolean allMatch = students.stream().allMatch(student -> student.getScore() == 100);
  5. 5. // 是否全部学生都没有100分
  6. 6. boolean noneMatch = students.stream().noneMatch(student -> student.getScore() == 100);
  7. 7. System.out.println(anyMatch);
  8. 8. System.out.println(allMatch);
  9. 9. System.out.println(noneMatch);
  10. 10.
  11. 11. // 输出结果
  12. 12. true
  13. 13. false
  14. 14. false

3.5 映射 map

映射,顾名思义,将一个对象映射成另外一个对象。即一个Stream流中的所有元素按照一定的映射规则,映射到另一个流中。映射有map和flatMap两种类型: 1、map:接收一个函数作为参数,此函数作用到Stream中每一个元素,形成一个新的元素,所有新的元素组成一个新的流。 2、flatMap:接收一个函数作为参数,它将流中的每个元素都转换成另一个流,然后把所有流再连接形成一个最终流。

  1. 1. // 获取每个学生的姓名
  2. 2. List<String> studentNames =
  3. 3. students.stream().map(Student::getName).collect(Collectors.toList());
  4. 4. System.out.println(studentNames);
  5. 5. // 每个学生的成绩加10分
  6. 6. List<Double> studentScores = students.stream().map(student -> student.getScore() + 10)
  7. 7. .collect(Collectors.toList());
  8. 8. System.out.println(studentScores);
  9. 9.
  10. 10. // 输出结果
  11. 11. [张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张]
  12. 12. [98.0, 70.0, 110.0, 20.0, 105.0, 65.0, 76.0, 110.0, 105.0, 100.0]
  1. 1. List<String> list = Arrays.asList("a-b-c-d", "g-h-i");
  2. 2. List<String> list1 = list.stream().flatMap(s -> Arrays.stream(s.split("-"))).collect(Collectors.toList());
  3. 3. System.out.println(list1);
  4. 4.
  5. 5. // 输出结果
  6. 6. [a, b, c, d, g, h, i]

3.6 截取流 limit

  1. 1. // limit方法用于获取指定数量的流。例如下面演示取出学习成绩大于70的5个人
  2. 2. List<Student> students2 = students.stream().filter(student -> student.getScore() > 70)
  3. 3. .limit(5).collect(Collectors.toList());
  4. 4. students2.forEach(System.out::println);
  5. 5. // 跳过第一个再取2个
  6. 6. List<Student> students8 = students.stream().skip(1).limit(2).collect(Collectors.toList());
  7. 7. // 获取5个int随机数,按从小到大排序
  8. 8. Random random = new Random();
  9. 9. random.ints().limit(5).sorted().forEach(System.out::println);
  10. 10.
  11. 11. // 输出结果
  12. 12. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  13. 13. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  14. 14. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  15. 15. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  16. 16. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  17. 17. -1490202714
  18. 18. 145340547
  19. 19. 368332155
  20. 20. 388399398
  21. 21. 1099579920

3.7 排序 sorted

sorted 方法用于对流中的元素进行排序,有两种排序: sorted():自然排序,流中元素需要实现Comparable接口。 sorted(Comparator<? super T> comparator):需要自定义排序器。

  1. 1. // 按成绩升序
  2. 2. List<Student> students3 = students.stream().sorted(Comparator.comparing(Student::getScore))
  3. 3. .collect(Collectors.toList());
  4. 4. System.out.println("按成绩升序");
  5. 5. students3.forEach(System.out::println);
  6. 6. // 按成绩降序
  7. 7. List<Student> students4 =
  8. 8. students.stream().sorted(Comparator.comparing(Student::getScore).reversed())
  9. 9. .collect(Collectors.toList());
  10. 10. System.out.println("按成绩降序");
  11. 11. students4.forEach(System.out::println);
  12. 12. // 按成绩升序,再按年龄升序
  13. 13. List<Student> students5 = students.stream()
  14. 14. .sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getAge))
  15. 15. .collect(Collectors.toList());
  16. 16. System.out.println("按成绩升序,再按年龄升序");
  17. 17. students5.forEach(System.out::println);
  18. 18. // 按成绩升序,再按年龄降序
  19. 19. List<Student> students6 = students.stream().sorted((s1, s2) -> {
  20. 20. if (s1.getScore() != s2.getScore()) {
  21. 21. return (int) (s1.getScore() - s2.getScore());
  22. 22. } else {
  23. 23. return (s2.getAge() - s1.getAge());
  24. 24. }
  25. 25. }).collect(Collectors.toList());
  26. 26. System.out.println("按成绩升序,再按年龄降序");
  27. 27. students6.forEach(System.out::println);

3.8 去重 distinct

  1. 1. List<String> list2 = Arrays.asList("a", "b", "a", "c", "f", "e", "f");
  2. 2. List<String> list3 = list2.stream().distinct().collect(Collectors.toList());
  3. 3. Set<String> stringSet = list2.stream().collect(Collectors.toSet()); // list转set也可以达到去重效果
  4. 4. System.out.println(list3);
  5. 5. System.out.println(stringSet);
  6. 6.
  7. 7. // 输出结果
  8. 8. [a, b, c, f, e]
  9. 9. [a, b, c, e, f]

3.9 统计 summaryStatistics

一些收集器能产生统计结果,例如Collectors提供了一系列用于数据统计的静态方法,它们主要用于int、double、long等基本类型上。

  1. 1. // 总和统计summaryStatistics
  2. 2. DoubleSummaryStatistics doubleSummaryStatistics =
  3. 3. students.stream().mapToDouble(Student::getScore).summaryStatistics();
  4. 4. System.out.println("平均值:" + doubleSummaryStatistics.getAverage());
  5. 5. System.out.println("总个数:" + doubleSummaryStatistics.getCount());
  6. 6. System.out.println("最大值:" + doubleSummaryStatistics.getMax());
  7. 7. System.out.println("最小值:" + doubleSummaryStatistics.getMin());
  8. 8. System.out.println("总和值:" + doubleSummaryStatistics.getSum());
  9. 9.
  10. 10. // 输出结果
  11. 11. 平均值:75.9
  12. 12. 总个数:10
  13. 13. 最大值:100.0
  14. 14. 最小值:10.0
  15. 15. 总和值:759.0
  1. 1. // 统计个数
  2. 2. long count = students.stream().count();
  3. 3. // 平均值
  4. 4. Double averageScore =
  5. 5. students.stream().collect(Collectors.averagingDouble(Student::getScore));
  6. 6. // 最大值和最小值
  7. 7. Optional<Double> maxScore = students.stream().map(Student::getScore).max(Double::compare);
  8. 8. Optional<Double> minScore = students.stream().map(Student::getScore).min(Double::compare);
  9. 9. // 求和
  10. 10. double sumScore = students.stream().mapToDouble(Student::getScore).sum();
  11. 11. // 一次性统计所有
  12. 12. DoubleSummaryStatistics doubleSummaryStatistics1 =
  13. 13. students.stream().collect(Collectors.summarizingDouble(Student::getScore));
  14. 14. System.out.println("单个维度计算:");
  15. 15. System.out.println("统计个数:" + count);
  16. 16. System.out.println("平均值:" + averageScore);
  17. 17. maxScore.ifPresent(aDouble -> System.out.println("最大值:" + aDouble));
  18. 18. minScore.ifPresent(aDouble -> System.out.println("最小值:" + aDouble));
  19. 19. System.out.println("求和:" + sumScore);
  20. 20. System.out.println("一次性统计所有:" + doubleSummaryStatistics1);
  21. 21.
  22. 22. // 输出结果
  23. 23. 单个维度计算:
  24. 24. 统计个数:10
  25. 25. 平均值:75.9
  26. 26. 最大值:100.0
  27. 27. 最小值:10.0
  28. 28. 求和:759.0

3.10 归约 reduce

归约,把一个流归约(缩减)成一个值,能实现对集合求和、求乘积和求最值等操作。

  1. 1. List<Integer> integerList = Arrays.asList(6, 7, 1, 10, 11, 7, 13, 20);
  2. 2. // 求和
  3. 3. Optional<Integer> sum1 = integerList.stream().reduce(Integer::sum);
  4. 4. // 求和,基于10的基础上
  5. 5. Integer sum2 = integerList.stream().reduce(10, Integer::sum);
  6. 6. // 求最大值
  7. 7. Optional<Integer> max1 = integerList.stream().reduce((x, y) -> x > y ? x : y);
  8. 8. // 求最大值,基于与50比较的基础上
  9. 9. Integer max2 = integerList.stream().reduce(50, Integer::max);
  10. 10. Optional<Integer> min = integerList.stream().reduce(Integer::min);
  11. 11. // 求乘积
  12. 12. Optional<Integer> product = integerList.stream().reduce((x, y) -> x * y);
  13. 13. System.out.println("原始集合:" + integerList);
  14. 14. System.out.println("集合求和:" + sum1.get() + "," + sum2);
  15. 15. System.out.println("集合求最大值:" + max1.get() + "," + max2);
  16. 16. System.out.println("集合求最小值:" + min.get());
  17. 17. System.out.println("集合求积:" + product.get());
  18. 18.
  19. 19. // 输出结果
  20. 20. 原始集合:[6, 7, 1, 10, 11, 7, 13, 20]
  21. 21. 集合求和:75,85
  22. 22. 集合求最大值:20,50
  23. 23. 集合求最小值:1
  24. 24. 集合求积:8408400

3.11 归集 toList,toSet,toMap

Java中的Stream不会存储元素,而是按需计算按照特定的规则对数据进行计算,一般会输出结果。所以流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。比较常用的是toList、toSet和toMap,以及复杂的toCollection、toConcurrentMap等。

  1. 1. // 获取学生名字,形成新的list集合
  2. 2. List<String> studentNames1 =
  3. 3. students.stream().map(Student::getName).collect(Collectors.toList());
  4. 4. // 获取年龄大于等于15的年龄set集合
  5. 5. Set<Integer> ageSet = students.stream().filter(student -> student.getAge() >= 15)
  6. 6. .map(Student::getAge).collect(Collectors.toSet());
  7. 7. // 创建学生ID和学生实体的map
  8. 8. Map<String, Student> studentMap =
  9. 9. students.stream().collect(Collectors.toMap(Student::getId, student -> student));
  10. 10. System.out.println(studentNames1);
  11. 11. System.out.println(ageSet);
  12. 12. studentMap.forEach((key, value) -> System.out.println(key + ":" + value));
  13. 13.
  14. 14. // 输出结果
  15. 15. [张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张]
  16. 16. [17, 18, 20, 21, 22, 25]
  17. 17. 1:Student{id='1', name='张三', age=18, sex=male, score=88.0}
  18. 18. 2:Student{id='2', name='李四', age=17, sex=male, score=60.0}
  19. 19. 3:Student{id='3', name='王五', age=18, sex=male, score=100.0}
  20. 20. 4:Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  21. 21. 5:Student{id='5', name='董七', age=14, sex=female, score=95.0}
  22. 22. 6:Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  23. 23. 7:Student{id='7', name='老九', age=20, sex=female, score=66.0}
  24. 24. 8:Student{id='8', name='小明', age=18, sex=male, score=100.0}
  25. 25. 9:Student{id='9', name='小红', age=22, sex=female, score=95.0}
  26. 26. 10:Student{id='10', name='小张', age=25, sex=male, score=90.0}

3.12 分组 partitioningBy,groupingBy

partitioningBy(分区):stream中的元素按条件被分为两个Map。 groupingBy(分组):stream中的元素按条件被分为多个Map。

  1. 1. // 按条件学生成绩是否大于等于60,划分为2个组
  2. 2. Map<Boolean, List<Student>> studentScorePart = students.stream()
  3. 3. .collect(Collectors.partitioningBy(student -> student.getScore() >= 60));
  4. 4. // 按性别分组
  5. 5. Map<String, List<Student>> studentSexMap =
  6. 6. students.stream().collect(Collectors.groupingBy(Student::getSex));
  7. 7. // 按年龄分组
  8. 8. Map<Integer, List<Student>> studentAgeMap =
  9. 9. students.stream().collect(Collectors.groupingBy(Student::getAge));
  10. 10. // 先按性别分组,再按年龄分组
  11. 11. Map<String, Map<Integer, List<Student>>> collect = students.stream().collect(
  12. 12. Collectors.groupingBy(Student::getSex, Collectors.groupingBy(Student::getAge)));
  13. 13. System.out.println("按条件学生成绩是否大于等于60,划分为2个组:");
  14. 14. studentScorePart.forEach((aBoolean, students7) -> {
  15. 15. System.out.println("成绩大于等于60?:" + aBoolean);
  16. 16. students7.forEach(System.out::println);
  17. 17. });
  18. 18. System.out.println("按性别分组:");
  19. 19. studentSexMap.forEach((sex, students7) -> {
  20. 20. System.out.println("性别?:" + sex);
  21. 21. students7.forEach(System.out::println);
  22. 22. });
  23. 23. System.out.println("按年龄分组:");
  24. 24. studentAgeMap.forEach((age, students7) -> {
  25. 25. System.out.println("年龄:" + age);
  26. 26. students7.forEach(System.out::println);
  27. 27. });
  28. 28. System.out.println("先按性别分组,再按年龄分组:");
  29. 29. collect.forEach((sex, integerListMap) -> {
  30. 30. System.out.println("性别:" + sex);
  31. 31. integerListMap.forEach((age, students7) -> {
  32. 32. System.out.println("年龄:" + age);
  33. 33. students7.forEach(System.out::println);
  34. 34. });
  35. 35. });
  36. 36.
  37. 37. //输出结果
  38. 38. 按条件学生成绩是否大于等于60,划分为2个组:
  39. 39. 成绩大于等于60?:false
  40. 40. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  41. 41. Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  42. 42. 成绩大于等于60?:true
  43. 43. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  44. 44. Student{id='2', name='李四', age=17, sex=male, score=60.0}
  45. 45. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  46. 46. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  47. 47. Student{id='7', name='老九', age=20, sex=female, score=66.0}
  48. 48. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  49. 49. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  50. 50. Student{id='10', name='小张', age=25, sex=male, score=90.0}
  51. 51. 按性别分组:
  52. 52. 性别?:female
  53. 53. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  54. 54. Student{id='7', name='老九', age=20, sex=female, score=66.0}
  55. 55. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  56. 56. 性别?:male
  57. 57. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  58. 58. Student{id='2', name='李四', age=17, sex=male, score=60.0}
  59. 59. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  60. 60. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  61. 61. Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  62. 62. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  63. 63. Student{id='10', name='小张', age=25, sex=male, score=90.0}
  64. 64. 按年龄分组:
  65. 65. 年龄:17
  66. 66. Student{id='2', name='李四', age=17, sex=male, score=60.0}
  67. 67. 年龄:18
  68. 68. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  69. 69. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  70. 70. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  71. 71. 年龄:20
  72. 72. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  73. 73. Student{id='7', name='老九', age=20, sex=female, score=66.0}
  74. 74. 年龄:21
  75. 75. Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  76. 76. 年龄:22
  77. 77. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  78. 78. 年龄:25
  79. 79. Student{id='10', name='小张', age=25, sex=male, score=90.0}
  80. 80. 年龄:14
  81. 81. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  82. 82. 先按性别分组,再按年龄分组:
  83. 83. 性别:female
  84. 84. 年龄:20
  85. 85. Student{id='7', name='老九', age=20, sex=female, score=66.0}
  86. 86. 年龄:22
  87. 87. Student{id='9', name='小红', age=22, sex=female, score=95.0}
  88. 88. 年龄:14
  89. 89. Student{id='5', name='董七', age=14, sex=female, score=95.0}
  90. 90. 性别:male
  91. 91. 年龄:17
  92. 92. Student{id='2', name='李四', age=17, sex=male, score=60.0}
  93. 93. 年龄:18
  94. 94. Student{id='1', name='张三', age=18, sex=male, score=88.0}
  95. 95. Student{id='3', name='王五', age=18, sex=male, score=100.0}
  96. 96. Student{id='8', name='小明', age=18, sex=male, score=100.0}
  97. 97. 年龄:20
  98. 98. Student{id='4', name='赵六', age=20, sex=male, score=10.0}
  99. 99. 年龄:21
  100. 100. Student{id='6', name='幺八', age=21, sex=male, score=55.0}
  101. 101. 年龄:25
  102. 102. Student{id='10', name='小张', age=25, sex=male, score=90.0}

3.13 合并 joining

将stream中的元素用指定的连接符(没有的话,则直接连接)连接成一个字符串。

  1. 1. String joinName = students.stream().map(Student::getName).collect(Collectors.joining(", "));
  2. 2. System.out.println(joinName);
  3. 3.
  4. 4. // 输出结果
  5. 5. 张三, 李四, 王五, 赵六, 董七, 幺八, 老九, 小明, 小红, 小张

四、演示代码获取

此演示代码程序已放到Github:https://github.com/LucioChn/java8-stream-demo
欢迎Star,给个支持!

作者:Μr.ηobοdy 链接:https://blog.csdn.net/chenlixiao007/article/details/112752413 来源:CSDN