一.什么是Stream?

1.流到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算!”
2.注意:

  • Stream自己不会存储元素

  • Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream

  • Stream操作是延迟执行的。这以为着他们会等到需要结果的时候才执行

    二.Stream的操作三个步骤

    1.创建Stream

    一个数据源(如:集合、数组),获取一个流

    2.中间操作

    一个中间操作链,对数据源的数据进行处理

    3.终止操作(终端操作)

    一个终止操作,执行中间操作链,并产生结果

    1.Stream的4种创建方式

    1.可以通过Collection系列集合提供的Stream()或者parallelStream()并行流 获取流

    1. List<String> list = new ArrayList<>();
    2. Stream<String> stream = list.stream();

    2.可以通过Arrays中的静态方法stream()获取数组流

    1. Employee[] employees = new Employee[10];
    2. Stream<Employee> employeeStream = Arrays.stream(employees);

    3.通过Stream类中的静态方法of()

    1. Stream<String> stringStream = Stream.of("aa", "bb", "cc");

    4.创建无限流

  • 迭代

    1. Stream<Integer> integerStream = Stream.iterate(0, (x) -> x + 2);
    2. integerStream.limit(10).forEach(System.out::println);
  • 生成

    1. Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println);

    2.Stream的中间操作:

    1.筛选与切片

    多个中间操作可以谅解起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。

  • filter(Predicate p):接收Lambda,从流中排除某些元素

  • distinct():筛选,通过流所生成元素的hashCode()和equals()去排除重复元素。注意:对象需要重写equals和hashcode
  • limit(long maxSize):截断流,使其元素不操作给定数量
  • skip(long n):跳过元素,返回一个扔掉了前n个元素的流。若扔掉的流中元素不足n个,则返回一个空流。与limit(n)互补

    1. //员工集合
    2. List<Employee> employeeList = Arrays.asList(
    3. new Employee("张三", 18, 6669.58),
    4. new Employee("李四", 12, 7779.58),
    5. new Employee("王五", 36, 9229.58),
    6. new Employee("赵六", 51, 19999.58),
    7. new Employee("田七", 20, 3399.58),
    8. new Employee("田七", 20, 3399.58),
    9. new Employee("田七", 20, 3399.58),
    10. new Employee("田七", 20, 3399.58)
    11. );

    ```java //filter //内部迭代:迭代操作由Stream API完成 @Test public void test1() {

    1. //中间操作:不会执行任何操作
    2. Stream<Employee> employeeStream = employeeList.stream().filter(x -> {
    3. System.out.println("Stream API 的中间操作");
    4. return (x.getAge() > 35);
    5. });
    6. //终止操作:一次性执行全部内容,即“惰性求值”
    7. employeeStream.forEach(System.out::println);

    } //外部迭代 @Test public void test2() {

    1. Iterator<Employee> iterator = employeeList.iterator();
    2. while (iterator.hasNext()) {
    3. System.out.println(iterator.next());
    4. }

    } //limit @Test public void test3() {

    1. employeeList.stream()
    2. .filter((x) -> {
    3. System.out.println("短路!");
    4. return x.getSalary() > 5000;
    5. })
    6. .limit(2)
    7. .forEach(System.out::println);

    } //skip @Test public void test4() {

    1. employeeList.stream()
    2. .filter((x) -> x.getSalary() > 5000)
    3. .skip(2)
    4. .forEach(System.out::println);

    } //distinct @Test public void test5() {

    1. employeeList.stream()
    2. .filter((x) -> x.getSalary() > 3000)
    3. .skip(2)
    4. .distinct()
    5. .forEach(System.out::println);

    }

  1. <a name="oxrpf"></a>
  2. ### 2.映射
  3. - **map:**接收 Lambda ,将元素转换为其他形式或提取信息;接受一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
  4. ```java
  5. @Test
  6. public void test6() {
  7. List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
  8. list.stream()
  9. .map((x) -> x.toUpperCase())
  10. .forEach(System.out::println);
  11. System.out.println("-------------------------------------------");
  12. employeeList.stream().map(Employee::getName).forEach(System.out::println);
  13. }
  • flatMap:接收一个函数作为参数,将流中每一个值都换成另一个流,然后把所有流重新连接成一个流

    1. @Test
    2. public void test7() {
    3. List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
    4. Stream<Stream<Character>> streamStream = list.stream()
    5. .map(TestStreamAPI2::filterCharacter);
    6. streamStream.forEach((x) -> x.forEach(System.out::println));
    7. System.out.println("-------------------------------------------");
    8. Stream<Character> characterStream = list.stream().flatMap(TestStreamAPI2::filterCharacter);
    9. characterStream.forEach(System.out::println);
    10. }

    3.排序

  • sorted():自然排序(Comparable)

  • sorted(Comparator c):定制排序(Comparator)
    1. @Test
    2. public void test8() {
    3. List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
    4. list.stream().sorted().forEach(System.out::println);
    5. System.out.println("-------------------------------------------");
    6. employeeList.stream().sorted((x, y) -> {
    7. if ((x.getAge() + "").equals(y.getAge() + "")) {
    8. return x.getName().compareTo(y.getName());
    9. } else {
    10. return (x.getAge() + "").compareTo(y.getAge() + "");
    11. }
    12. }).forEach(System.out::println);
    13. }

    3.Stream的终止操作:

    collect(Collector c):将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
    Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下:

1.查找

  • allMatch:检查是否匹配所有元素
  • anyMatch:检查是否至少匹配一个元素
  • noneMatch:检查是否没有匹配所有元素
  • findFirst:返回第一个元素
  • findAny:返回当前流中的任意元素

    1. @Test
    2. public void test1() {
    3. boolean allMatch = employeeList
    4. .stream()
    5. .allMatch((x) -> x.getStatus() == Status.VOCATION);
    6. System.out.println(allMatch);
    7. System.out.println("-------------------------------------------");
    8. boolean anyMatch = employeeList
    9. .stream()
    10. .anyMatch((x) -> x.getStatus() == Status.VOCATION);
    11. System.out.println(anyMatch);
    12. System.out.println("-------------------------------------------");
    13. boolean noneMatch = employeeList
    14. .stream()
    15. .noneMatch((x) -> x.getStatus() == Status.VOCATION);
    16. System.out.println(noneMatch);
    17. System.out.println("-------------------------------------------");
    18. Optional<Employee> optionalEmployee = employeeList
    19. .stream()
    20. .sorted((x, y) -> Double.compare(x.getSalary(), y.getSalary())).findFirst();
    21. System.out.println(optionalEmployee.get());
    22. System.out.println("-------------------------------------------");
    23. Optional<Employee> any = employeeList
    24. .stream()
    25. .filter((e) -> e.getStatus() == Status.Busy)
    26. .findAny();
    27. System.out.println(any.get());
    28. }

    2.匹配

  • count:返回流中元素的总个数

  • max:返回流中最大值
  • min:返回流中最小值

    1. @Test
    2. public void test2() {
    3. long count = employeeList.stream().count();
    4. System.out.println(count);
    5. System.out.println("-------------------------------------------");
    6. Optional<Employee> maxEmployee = employeeList
    7. .stream()
    8. .max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
    9. System.out.println(maxEmployee.get());
    10. System.out.println("-------------------------------------------");
    11. Optional<Double> min = employeeList
    12. .stream()
    13. .map(Employee::getSalary)
    14. .min(Double::compare);
    15. System.out.println(min.get());
    16. }

    3.归约

    reduce(T identity, BinaryOperator) / reduce(BinaryOperator) 可以将流中的数据反复结合起来,得到一个值

    1. @Test
    2. public void test3() {
    3. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    4. Integer reduce = list.stream()
    5. .reduce(0, (x, y) -> x + y);
    6. System.out.println(reduce);
    7. System.out.println("-------------------------------------------");
    8. Double empReduce = employeeList.stream()
    9. .map(Employee::getSalary)
    10. .reduce(0d, (x, y) -> x + y);
    11. System.out.println(empReduce);
    12. System.out.println("-------------------------------------------");
    13. Optional<Double> doubleOptional = employeeList.stream()
    14. .map(Employee::getSalary)
    15. .reduce(Double::sum);
    16. System.out.println(doubleOptional.get());
    17. }

    4.收集

    collect 将流转换成其他形式;接收一个 Collector 接口的实现,用于给流中元素做汇总的方法

  • 获取属性值集合

    1. @Test
    2. public void test4() {
    3. List<String> collectList = employeeList
    4. .stream()
    5. .map(Employee::getName)
    6. .collect(Collectors.toList());
    7. System.out.println(collectList);
    8. System.out.println("-------------------------------------------");
    9. Set<String> collectSet = employeeList
    10. .stream()
    11. .map(Employee::getName)
    12. .collect(Collectors.toSet());
    13. System.out.println(collectSet);
    14. System.out.println("-------------------------------------------");
    15. HashSet<String> collectHashSet = employeeList
    16. .stream()
    17. .map(Employee::getName)
    18. .collect(Collectors.toCollection(HashSet::new));
    19. System.out.println(collectHashSet);
    20. }
  • 总数、平均值、总和

    1. @Test
    2. public void test5() {
    3. //总数
    4. employeeList.stream().collect(Collectors.counting());
    5. //平均值
    6. employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
    7. //总和
    8. employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary));
    9. //工资最大的员工信息
    10. Optional<Employee> maxEmp = employeeList.stream().collect(Collectors.maxBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
    11. //工资最小的值
    12. Optional<Double> minEmp = employeeList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));
    13. }
  • 分组与多级分组

    1. //分组
    2. @Test
    3. public void test6() {
    4. Map<Status, List<Employee>> statusListMap = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus));
    5. System.out.println(statusListMap);
    6. }
    7. //多级分组
    8. @Test
    9. public void test7() {
    10. Map<Status, Map<String, List<Employee>>> collect = employeeList.stream().
    11. collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
    12. if (((Employee) e).getAge() <= 35) {
    13. return "青年";
    14. } else if (((Employee) e).getAge() <= 50) {
    15. return "中年";
    16. } else {
    17. return "老年";
    18. }
    19. })));
    20. }
  • 分区:满足条件的分一个区,不满足条件的分一个区。

    1. @Test
    2. public void test8() {
    3. Map<Boolean, List<Employee>> collect = employeeList
    4. .stream()
    5. .collect(Collectors.partitioningBy((e) -> e.getSalary() > 5000));
    6. System.out.println(collect);
    7. }
  • 拼接

    1. @Test
    2. public void test10() {
    3. String collect = employeeList.stream()
    4. .map(Employee::getName)
    5. .collect(Collectors.joining(",", "[", "]"));
    6. System.out.println(collect);
    7. }

    三.Stream API练习

    1. /**
    2. *交易人
    3. **/
    4. @Data
    5. @AllArgsConstructor
    6. @NoArgsConstructor
    7. public class Trader {
    8. private String name;//姓名
    9. private String city;//居住地
    10. }
    11. /**
    12. *交易实体
    13. **/
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. public class Transaction {
    18. private Trader trader;
    19. private int year;//年份
    20. private int value;//交易额
    21. }
    1. List<Transaction> transactions = null;
    2. @BeforeEach
    3. public void before() {
    4. Trader raoul = new Trader("Raoul", "Cambridge");
    5. Trader mario = new Trader("Mario", "Milan");
    6. Trader alan = new Trader("Alan", "Cambridge");
    7. Trader brian = new Trader("Brian", "Cambridge");
    8. transactions = Arrays.asList(
    9. new Transaction(brian, 2011, 300),
    10. new Transaction(raoul, 2012, 1000),
    11. new Transaction(raoul, 2011, 400),
    12. new Transaction(mario, 2012, 710),
    13. new Transaction(mario, 2012, 700),
    14. new Transaction(alan, 2012, 950)
    15. );
    16. }
    17. //1.找出2011年发生的所有交易,并按照交易额排序,由高到低
    18. @Test
    19. public void test1() {
    20. transactions
    21. .stream()
    22. .filter((x) -> x.getYear() == 2011)
    23. .sorted((x, y) -> -Integer.compare(x.getValue(), y.getValue()))
    24. .forEach(System.out::println);
    25. }
    26. //2.交易员都在哪些不同的城市工作过?
    27. @Test
    28. public void test2() {
    29. transactions
    30. .stream()
    31. .map(Transaction::getTrader)
    32. .map(Trader::getCity)
    33. .distinct()
    34. .forEach(System.out::println);
    35. }
    36. //3.查找所有来自剑桥的交易员,并按照姓名排序
    37. @Test
    38. public void test3() {
    39. transactions
    40. .stream()
    41. .filter((x) -> x.getTrader().getCity().equals("Cambridge"))
    42. .map(Transaction::getTrader)
    43. .distinct()
    44. .sorted((x, y) -> x.getName().compareTo(y.getName()))
    45. .forEach(System.out::println);
    46. }
    47. //4.返回所有交易员的姓名字符串
    48. @Test
    49. public void test4() {
    50. String collect = transactions
    51. .stream()
    52. .map(Transaction::getTrader)
    53. .map(Trader::getName)
    54. .distinct()
    55. .collect(Collectors.joining(","));
    56. System.out.println(collect);
    57. }
    58. //5.有没有交易员是在米兰工作的
    59. @Test
    60. public void test5() {
    61. boolean milan = transactions.stream().anyMatch((t) -> t.getTrader().getCity().equals("Milan"));
    62. System.out.println(milan);
    63. }
    64. //6.打印生活在剑桥的交易员的所有交易额
    65. @Test
    66. public void test6() {
    67. Integer cambridge = transactions
    68. .stream()
    69. .filter((x) -> x.getTrader().getCity().equals("Cambridge"))
    70. .map(Transaction::getValue)
    71. .reduce(0, Integer::sum);
    72. System.out.println(cambridge);
    73. }
    74. //7.所有交易中,最高的交易额是多少
    75. @Test
    76. public void test7() {
    77. Optional<Integer> max = transactions
    78. .stream()
    79. .map(Transaction::getValue)
    80. .max(Integer::compare);
    81. System.out.println(max.get());
    82. }
    83. //8.找到交易额最小的交易
    84. @Test
    85. public void test8() {
    86. Optional<Transaction> min = transactions
    87. .stream()
    88. .min((x, y) -> Integer.compare(x.getValue(), y.getValue()));
    89. System.out.println(min.get());
    90. }

    四.并行流与串行流

    1.并行流:

    就是把一个内容分成几个数据块,并用不同的线程分别处理每个数据块的流。
    Java 8 中将并行进行了优化,我们可以很容易的对数据进行操作;Stream API 可以声明性地通过 parallel() 与 sequential() 在并行流与串行流之间切换。

    2.了解Fork/Join框架

    1.Fork/Join框架:

    就是在必要的情况下,将一个大人物,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join汇总。

    2.Fork/Join框架与传统线程池的区别:

  • 采用“工作窃取”模式(work-stealing):

当执行新的任务时它可以将其拆分分成更小的任务执行,并将小人物加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。
相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行。这种方式减少了线程的等待时间,提高了性能。

  1. public class ForkJoinCalculate extends RecursiveTask<Long> {
  2. private static final long serialVersionUID = 1234567890L;
  3. private long start;
  4. private long end;
  5. private static final long THRESHOLD = 100000;
  6. public ForkJoinCalculate(long start, long end) {
  7. this.start = start;
  8. this.end = end;
  9. }
  10. @Override
  11. protected Long compute() {
  12. long length = end - start;
  13. if (length <= THRESHOLD) {
  14. long sum = 0;
  15. for (long i = start; i <= end; i++) {
  16. sum += i;
  17. }
  18. return sum;
  19. } else {
  20. long middle = (start + end) / 2;
  21. ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
  22. left.fork();//拆分子任务,同时压入线程队列
  23. ForkJoinCalculate right = new ForkJoinCalculate(middle + 1, end);
  24. right.fork();
  25. return left.join() + right.join();
  26. }
  27. }
  28. }
  1. /**
  2. * ForkJoin框架
  3. */
  4. @Test
  5. public void test1() {
  6. Instant start = Instant.now();
  7. ForkJoinPool pool = new ForkJoinPool();
  8. ForkJoinTask<Long> task = new ForkJoinCalculate(0, 100000000000L);
  9. Long sum = pool.invoke(task);
  10. System.out.println(sum);
  11. Instant end = Instant.now();
  12. System.out.println("完成时间:" + Duration.between(start, end).toMillis());
  13. }
  14. /**
  15. * 普通for循环
  16. */
  17. @Test
  18. public void test2() {
  19. Instant start = Instant.now();
  20. long sum = 0L;
  21. for (long i = 0; i <= 100000000000L; i++) {
  22. sum += i;
  23. }
  24. System.out.println(sum);
  25. Instant end = Instant.now();
  26. System.out.println("完成时间:" + Duration.between(start, end).toMillis());
  27. }
  28. /**
  29. * java8并行流
  30. *串行流(单线程):切换为并行流 parallel()
  31. *并行流:切换为串行流 sequential()
  32. */
  33. @Test
  34. public void test3() {
  35. Instant start = Instant.now();
  36. long reduce = LongStream
  37. .rangeClosed(0, 100000000000L)
  38. .parallel()//底层:ForkJoin 并行执行
  39. .reduce(0, Long::sum);
  40. System.out.println(reduce);
  41. Instant end = Instant.now();
  42. System.out.println("完成时间:" + Duration.between(start, end).toMillis());
  43. }