1.Stream API的理解:

1.1 Stream关注的是对数据的运算,与CPU打交道
集合关注的是数据的存储,与内存打交道

1.2 java8提供了一套api,使用这套api可以对内存中的数据进行过滤、排序、映射、归约等操作。类似于sql对数据库中表的相关操作。

2.注意点:

①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

3.Stream的使用流程:

① Stream的实例化
② 一系列的中间操作(过滤、映射、…)
③ 终止操作

4.使用流程的注意点:

4.1 一个中间操作链,对数据源的数据进行处理
4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

5.步骤一:Stream实例化

  1. //创建 Stream方式一:通过集合
  2. @Test
  3. public void test1(){
  4. List<Employee> employees = EmployeeData.getEmployees();
  5. // default Stream<E> stream() : 返回一个顺序流
  6. Stream<Employee> stream = employees.stream();
  7. // default Stream<E> parallelStream() : 返回一个并行流
  8. Stream<Employee> parallelStream = employees.parallelStream();
  9. }
  10. //创建 Stream方式二:通过数组
  11. @Test
  12. public void test2(){
  13. int[] arr = new int[]{1,2,3,4,5,6};
  14. //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
  15. IntStream stream = Arrays.stream(arr);
  16. Employee e1 = new Employee(1001,"Tom");
  17. Employee e2 = new Employee(1002,"Jerry");
  18. Employee[] arr1 = new Employee[]{e1,e2};
  19. Stream<Employee> stream1 = Arrays.stream(arr1);
  20. }
  21. //创建 Stream方式三:通过Stream的of()
  22. @Test
  23. public void test3(){
  24. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
  25. }
  26. //创建 Stream方式四:创建无限流
  27. @Test
  28. public void test4(){
  29. // 迭代
  30. // public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
  31. //遍历前10个偶数
  32. Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
  33. // 生成
  34. // public static<T> Stream<T> generate(Supplier<T> s)
  35. Stream.generate(Math::random).limit(10).forEach(System.out::println);
  36. }

6.步骤二:中间操作

image.png
image.png
image.png

7.步骤三:终止操作

image.png
image.png
image.png
image.png

Collector需要使用Collectors提供实例。

image.png