一、了解Stream

  1. StreamJava8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作

二、什么是Stream

  1. 流(Stream)到底是什么呢?
  2. 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
  3. “集合讲的是数据,流讲的是计算!”。
  4. 注意:
  5. 1)、Stream自己不会存储元素。
  6. 2)、Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream
  7. 3)、Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

三、Stream的操作三个步骤

  1. 三、Stream的操作三个步骤
  2. 1)、创建Stream
  3. 一个数据源(如:集合、数组),获取一个流
  4. 2)、中间操作
  5. 一个中间操作链,对数据源的数据进行处理
  6. 3)、终止操作(终端操作)
  7. 一个终止操作,执行中间操作链,并产生结果。

注意:java中:>>>和>>区别

  1. >>>表示不带符号向右移动二进制数,移动后前面统统补0;两个箭头表示带符号移动
  2. 没有<<<这种运算符,因为左移都是补零,没有正负数的区别。
  3. -12 的二进制为:1111 1111 1111 1111 1111 1111 1111 0100
  4. -12 >> 3 即带符号右移3位,结果是:1111 1111 1111 1111 1111 1111 1111 1110,十进制为: -2
  5. -12 >>> 3 就是右移三位,前面补零,为:0001 1111 1111 1111 1111 1111 1111 1110,十进制为:536870910

四、创建Stream

  1. // 可以通过Collection系列集合提供的stream()或parallelStream()
  2. List<String> list = new ArrayList<String>();
  3. Stream<String> stream1 = list.stream();
  4. //通过Arrays中的静态方法stream()获取数组流
  5. Employee[] emps = new Employee[10];
  6. Stream<Employee> stream2 = Arrays.stream(emps);
  7. // 通过Stream类中的静态方法of()
  8. Stream<String> stream3 = Stream.of("aa", "bb", "cc");
  9. stream3.forEach(System.out::println);
  10. //创建无限流
  11. // 迭代
  12. Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
  13. stream4.limit(10).forEach(System.out::println);
  14. // 生产
  15. Stream.generate( () -> Math.random()).limit(5).forEach(System.out::println);

五、中间操作

5.1、筛选与切片

  1. // 5.1.1、filter——接收 Lambda , 从流中排除某些元素。
  2. //
  3. emps.stream().filter((e)->e.getAge() > 18)
  4. .forEach(System.out::println);
  5. // 5.1.2、limit——截断流,使其元素不超过给定数量。
  6. emps.stream().filter((e)-> e.getAge()>18)
  7. .limit(2).forEach(System.out::println);
  8. // 5.1.3、 skip(n) ——跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  9. emps.stream().filter((e)->e.getAge()>18)
  10. .skip(2).forEach(System.out::println);
  11. // 5.1.4、distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
  12. emps.stream().distinct().forEach(System.out::println);

5.2、映射

  1. 5.2.1map-接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
  2. 5.2.2flatMap-接收一个函数作为参数,将流中的每个值都转换成另一个流,然后把所有流连接成一个流
  3. List<String> list = Arrays.asList("aaa", "bbb", "ccc");
  4. list.stream().map((str)->str.toUpperCase())
  5. .forEach(System.out::println);
  6. System.out.println("------");
  7. List<Employee> emps = Arrays.asList(
  8. new Employee(102, "李四", 59, 6666.66),
  9. new Employee(101, "张三", 18, 9999.99),
  10. new Employee(103, "王五", 28, 3333.33),
  11. new Employee(104, "赵六", 8, 7777.77),
  12. new Employee(104, "赵六", 8, 7777.77),
  13. new Employee(104, "赵六", 8, 7777.77),
  14. new Employee(105, "田七", 38, 5555.55)
  15. );
  16. emps.stream()
  17. .map(Employee::getName)
  18. .forEach(System.out::println);
  19. //流中流
  20. Stream<Stream<Character>> stream = list.stream()
  21. .map(TestStream::filterCharacter);
  22. stream.forEach(sm->{
  23. sm.forEach(System.out::println);
  24. });
  25. Stream<Character> flatMap = list.stream()
  26. .flatMap(TestStream::filterCharacter);
  27. flatMap.forEach(System.out::println);
  28. }
  29. /**
  30. * 测试map跟flatMap的区别
  31. * 有点跟集合中的add跟addAll方法类似
  32. * add是将无论是元素还是集合,整体加到其中一个集合中去[1,2,3.[2,3]]
  33. * addAll是将无论是元素还是集合,都是将元素加到另一个集合中去。[1,2,3,2,3]
  34. * @param str
  35. * @return
  36. */
  37. public static Stream<Character> filterCharacter(String str) {
  38. List<Character> list = new ArrayList<>();
  39. for( Character character:str.toCharArray()){
  40. list.add(character);
  41. }
  42. return list.stream();
  43. }

5.3、排序

  1. 5.3.1sorted()---自然排序(Comparable
  2. 5.3.2sorted(Comparator com)----定制排序(Comparator
  3. List<String> list = Arrays.asList("aa", "cc", "dd","ee");
  4. list.stream().sorted().forEach(System.out::println);
  5. System.out.println("=====");
  6. List<Employee> emps = Arrays.asList(
  7. new Employee(102, "李四", 59, 6666.66),
  8. new Employee(101, "张三", 18, 9999.99),
  9. new Employee(103, "王五", 28, 3333.33),
  10. new Employee(104, "赵六", 8, 7777.77),
  11. new Employee(104, "赵六", 8, 7777.77),
  12. new Employee(104, "赵六", 8, 7777.77),
  13. new Employee(105, "田七", 38, 5555.55)
  14. );
  15. emps.stream().sorted((x,y)-> {
  16. if (x.getAge() == y.getAge()) {
  17. return x.getName().compareTo(y.getName());
  18. } else {
  19. return Integer.compare(x.getAge(), y.getAge());
  20. }
  21. }).forEach(System.out::println);

六、终止操作

6.1、查找与匹配

  1. allMatch——检查是否匹配所有元素
  2. anyMatch——检查是否至少匹配一个元素
  3. noneMatch——检查是否没有匹配的元素
  4. findFirst——返回第一个元素
  5. findAny——返回当前流中的任意元素
  6. count——返回流中元素的总个数
  7. max——返回流中最大值
  8. min——返回流中最小值
  9. List<Employee2> emps = Arrays.asList(
  10. new Employee2(102, "李四", 59, 6666.66, Employee2.Status.BUSY.BUSY),
  11. new Employee2(101, "张三", 18, 9999.99, Employee2.Status.FREE),
  12. new Employee2(103, "王五", 28, 3333.33, Employee2.Status.VOCATION),
  13. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.BUSY),
  14. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.FREE),
  15. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.FREE),
  16. new Employee2(105, "田七", 38, 5555.55, Employee2.Status.BUSY)
  17. );
  18. System.out.println("allMatch");
  19. // allMatch
  20. boolean allMath = emps.stream().allMatch((e)->e.getStatus().equals(Employee2.Status.BUSY));
  21. System.out.println(allMath);
  22. System.out.println("anyMatch");
  23. // anyMatch
  24. boolean anyMath = emps.stream().anyMatch((e)->e.getAge()>18);
  25. System.out.println(anyMath);
  26. System.out.println("noneMatch");
  27. // noneMatch
  28. boolean noneMath = emps.stream().noneMatch((e)->e.getStatus().equals(Employee2.Status.BUSY));
  29. System.out.println(noneMath);
  30. System.out.println("findFirst");
  31. // findFirst
  32. Optional<Employee2> findFirst = emps.stream().sorted((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary())).findFirst();
  33. System.out.println(findFirst);
  34. // findAny
  35. System.out.println("findAny");
  36. Optional<Employee2> findAny = emps.stream().filter((e)->e.getStatus().equals(Employee2.Status.BUSY))
  37. .findAny();
  38. System.out.println(findAny);
  39. // count
  40. System.out.println("count");
  41. long count = emps.stream().count();
  42. System.out.println(count);
  43. // max
  44. System.out.println("max");
  45. // Optional<Double> max = emps.stream().max(Employee2::getSalary).map(Double::compare);
  46. // System.out.println(max);
  47. // min
  48. System.out.println("min");
  49. Optional<Employee2> min = emps.stream().min((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary()));
  50. System.out.println(min);

6.2、归约

  1. 6.2.1reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
  2. List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
  3. Integer sum = list.stream().reduce(0,(x,y)->x+y);
  4. System.out.println(sum);

6.3、收集

  1. Collector接口中方法的实现决定了如何对流执行收集操作(如收集到ListSetMap)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:
  2. 6.3.1Collectors.toList()
  3. List<Employee2> emps = Arrays.asList(
  4. new Employee2(102, "李四", 59, 6666.66, Employee2.Status.BUSY.BUSY),
  5. new Employee2(101, "张三", 18, 9999.99, Employee2.Status.FREE),
  6. new Employee2(103, "王五", 28, 3333.33, Employee2.Status.VOCATION),
  7. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.BUSY),
  8. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.FREE),
  9. new Employee2(104, "赵六", 8, 7777.77, Employee2.Status.FREE),
  10. new Employee2(105, "田七", 38, 5555.55, Employee2.Status.BUSY)
  11. );
  12. System.out.println("toList");
  13. // Collectors.toList()
  14. List<String> collect = emps.stream().map(Employee2::getName).collect(Collectors.toList());
  15. collect.forEach(System.out::println);
  16. System.out.println("toSet");
  17. // 6.3.2、Collectors.toSet()
  18. Set<String> collect2 = emps.stream().map(Employee2::getName)
  19. .collect(Collectors.toSet());
  20. collect2.forEach(System.out::println);
  21. //6.3.3、Collectors.toCollection(HashSet::new)
  22. System.out.println("toCollection");
  23. HashSet<String> collect3 = emps.stream().map(Employee2::getName).collect(Collectors.toCollection(HashSet::new));
  24. System.out.println(collect3);
  25. System.out.println("maxBy");
  26. //6.3.4、Collectors.maxBy()
  27. Optional<Double> collect5 = emps.stream()
  28. .map(Employee2::getSalary).collect(Collectors.maxBy(Double::compare));
  29. System.out.println(collect5.get());
  30. // 6.3.5、Collectors.minBy()
  31. System.out.println("minBy");
  32. Optional<Double> collect4 = emps.stream()
  33. .map(Employee2::getSalary).collect(Collectors.minBy(Double::compare));
  34. System.out.println(collect4);
  35. // 6.3.6、Collectors.summingDouble()
  36. System.out.println("summingDouble");
  37. Double collect6 = emps.stream().collect(Collectors.summingDouble(Employee2::getSalary));
  38. System.out.println(collect6);
  39. // 6.3.7、Collectors.averagingDouble()
  40. System.out.println("averagingDouble");
  41. Double collect7 = emps.stream()
  42. .collect(Collectors.averagingDouble((e)->e.getSalary()));
  43. System.out.println(collect7);
  44. // 6.3.8、Collectors.counting()
  45. System.out.println("counting");
  46. Long collect8 = emps.stream().collect(Collectors.counting());
  47. System.out.println(collect8);
  48. // 6.3.9、Collectors.summarizingDouble()
  49. System.out.println("summarizingDouble");
  50. // Long collect9 = emps.stream().collect(Collectors.summingDouble)
  51. // 6.3.10、分组Collectors.groupingBy()
  52. System.out.println("groupingBy");
  53. Map<Employee2.Status, List<Employee2>> collect10
  54. = emps.stream()
  55. .collect(Collectors.groupingBy((e)->e.getStatus()));
  56. System.out.println(collect10);
  57. // 6.3.11、多级分组Collectors.groupingBy()
  58. // 6.3.12、分区Collectors.partitioningBy()
  59. System.out.println("partitioningBy");
  60. // 6.3.13、组接字符串Collectors.joining()
  61. System.out.println("joining");