当前位置:   article > 正文

java8--强大的Stream API_java 8 stream api

java 8 stream api

目录

一、Stream API 说明

二、Stream的概述及使用

1.Stream的四种创建方式

方式一:通过集合

方式二:通过数组

方式三:通过Stream的of()

 方法四:创建无限流

2.Stream的中间操作

1.筛选与切片

2.映射

3.排序

3.Stream的终止操作

1.匹配与查找

2.归档

3.收集


一、Stream API 说明

二、Stream的概述及使用

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

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

3.Stream 执行流程
①Stream的实例化
②一系列的中间操作(过滤、映射、...)
③终止操作

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

1.Stream的四种创建方式

方式一:通过集合

Java8中的Collection接口被扩展,提供了两个获取流的方法:

  • default Stream<E> stream():返回一个顺序流
  • default Stream<E> parallelStream():返回一个并行流
  1. @Test
  2. public void test1() {//方式一:通过集合
  3. List<Employee> employees = Employee.getEmployees();
  4. //default Stream<E> stream():返回一个顺序流
  5. Stream<Employee> stream = employees.stream();
  6. //default Stream<E> parallelStream():返回一个并行流
  7. Stream<Employee> employeeStream = employees.parallelStream();
  8. }

方式二:通过数组

Java8中的Arrays的静态方法stream()可以获取数组流:

  • static <T> Stream<T> stream(T[] array):返回一个流

重载形式,能够处理对应基本类型的数组:

  • public static IntStream stream(int[] array)
  • public static LongStream stream(long[] array)
  • public static DoubleStream stream(double[] array)
  1. @Test
  2. public void test2() {//方式二:通过数组
  3. //public static IntStream stream(int[] array)
  4. //public static LongStream stream(long[] array)
  5. //public static DoubleStream stream(double[] array)
  6. int[] ints = new int[]{1, 2, 3, 4, 5, 6};
  7. IntStream intStream = Arrays.stream(ints);
  8. }

方式三:通过Stream的of()

可以调用Stream类静态方法of(),通过显示值创建一个流。它可以接收任意数量的参数。

  • public static<T>  Stream<T>  of(T... values):返回一个流
  1. @Test
  2. public void test3() {//方式三:通过Stream的of()
  3. //public static<T> Stream<T> of(T... values):返回一个流
  4. Stream<String> stringStream = Stream.of("tom", "小米", "小明");
  5. Employee[] employees = new Employee[]{new Employee("小红"), new Employee("小蓝")};
  6. Stream<Employee> employeeStream = Stream.of(employees);
  7. }

 方法四:创建无限流

可以使用具体方法Stream.iterate()和Stream.generate(),创建无限流。

  • 迭代:public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)
  • 生成:public static<T> Stream<T> generate(Supplier<T> s)
  1. @Test
  2. public void test4() {//方法四:创建无限流
  3. //迭代:public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)
  4. Stream.iterate(0, t -> t + 1).limit(10).forEach(System.out::println);
  5. //生成:public static<T> Stream<T> generate(Supplier<T> s)
  6. Stream.generate(Math::random).limit(10).forEach(System.out::println);
  7. }

2.Stream的中间操作

1.筛选与切片

代码使用案例:

  1. @Test
  2. public void test1() {
  3. List<Employee> list = Employee.getEmployees();
  4. //filter(Predicate p) --接收Lambda,从流中排除某些元素。
  5. Stream<Employee> stream = list.stream();
  6. stream.forEach(System.out::println);
  7. System.out.println();
  8. //注意stream对象已经不能再使用了!!!
  9. //练习:查询员工表中薪资大于10000的员工信息
  10. list.stream().filter(employee -> employee.getSalary() > 10000).forEach(System.out::println);
  11. System.out.println();
  12. //limit(n) --截断流,使其元素不超过给定数量
  13. list.stream().limit(2).forEach(System.out::println);
  14. System.out.println();
  15. //skip(n) --跳过n个元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回空流。
  16. //与limit(n)互补
  17. list.stream().skip(2).forEach(System.out::println);
  18. System.out.println();
  19. //distinct() --筛选,通过流所生成元素的hashCode()和equals()去除重复元素
  20. list.add(new Employee("Tom", 5000.0));
  21. list.add(new Employee("Tom", 5000.0));
  22. list.add(new Employee("Tom", 5000.0));
  23. list.stream().distinct().forEach(System.out::println);
  24. }
  25. //控制台输出如下
  26. Employee(name=小明, salary=9000.0)
  27. Employee(name=Tom, salary=10000.0)
  28. Employee(name=Daicy, salary=12000.0)
  29. Employee(name=Daicy, salary=12000.0)
  30. Employee(name=小明, salary=9000.0)
  31. Employee(name=Tom, salary=10000.0)
  32. Employee(name=Daicy, salary=12000.0)
  33. Employee(name=小明, salary=9000.0)
  34. Employee(name=Tom, salary=10000.0)
  35. Employee(name=Daicy, salary=12000.0)
  36. Employee(name=Tom, salary=5000.0)
  37. Process finished with exit code 0

2.映射

代码使用案例:

  1. //映射
  2. @Test
  3. public void test2() {
  4. //map(Function f) --接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被
  5. List<String> list = Arrays.asList("aa", "cc", "bb", "dd");
  6. list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
  7. System.out.println();
  8. //练习1:获取员工姓名长度大于3的员工的姓名
  9. List<Employee> employeeList = Employee.getEmployees();
  10. employeeList.stream().map(employee -> employee.getName())
  11. .filter(name -> name.length() > 3).forEach(System.out::println);
  12. //我觉得可以不用map,实践对此题来说效果一样
  13. //employeeList.stream().filter(employee -> employee.getName().length() > 3)
  14. // .forEach(employee -> System.out.println(employee.getName()));
  15. System.out.println();
  16. //练习2:获取list集合中字符串中的每个字符
  17. Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest2::fromStringToStream);
  18. streamStream.forEach(s -> {
  19. s.forEach(System.out::println);
  20. });
  21. System.out.println();
  22. //flatMap(Function f) --接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流串连成一个流
  23. list.stream().flatMap(StreamAPITest2::fromStringToStream).forEach(System.out::println);
  24. }
  25. //将字符串中的多个字符构成的集合转换为对应的Stream的实例
  26. public static Stream<Character> fromStringToStream(String str) {//aa
  27. ArrayList<Character> list = new ArrayList<>();
  28. for (char c : str.toCharArray()) {
  29. list.add(c);
  30. }
  31. return list.stream();
  32. }

3.排序

代码使用案例:

  1. //排序
  2. @Test
  3. public void test3() {
  4. //sorted() --自然排序
  5. List<Integer> list = Arrays.asList(12, 44, 75, 43, 88, 0, -23, 9, -67);
  6. list.stream().sorted().forEach(System.out::println);
  7. //抛异常,原因:Employee没有实现Comparable接口
  8. //Employee.getEmployeeList().stream().sorted().forEach(System.out::println);
  9. System.out.println();
  10. //sorted(Comparator com) --定制排序
  11. List<Employee> employeeList = Employee.getEmployeeList();
  12. employeeList.stream().sorted((e1, e2) -> {
  13. int ageValue = Integer.compare(e1.getAge(), e2.getAge());
  14. if (ageValue == 0) {//如果age相等,则根据salary从大到小排序
  15. return -Double.compare(e1.getSalary(), e2.getSalary());
  16. } else {
  17. return ageValue;
  18. }
  19. }).forEach(System.out::println);
  20. }
  21. //控制台输出
  22. -67
  23. -23
  24. 0
  25. 9
  26. 12
  27. 43
  28. 44
  29. 75
  30. 88
  31. Employee(name=小明, salary=9000.0, age=18)
  32. Employee(name=Daicy, salary=12000.0, age=25)
  33. Employee(name=Tom, salary=10000.0, age=25)

3.Stream的终止操作

1.匹配与查找


代码使用案例:



2.归档

代码使用案例:

3.收集

代码使用案例:

  1. //收集
  2. @Test
  3. public void test4() {
  4. //collect(Collector c) --将流转换为其他形式。
  5. // 接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
  6. //练习1:查找工资大于6000的员工,结果返回为一个List或Set
  7. List<Employee> employees = Employee.getEmployeeList();
  8. List<Employee> employeeList = employees.stream()
  9. .filter(emp -> emp.getSalary() > 6000).collect(Collectors.toList());
  10. Set<Employee> employeeSet = employees.stream()
  11. .filter(emp -> emp.getSalary() > 6000).collect(Collectors.toSet());
  12. employeeList.forEach(System.out::println);
  13. employeeSet.forEach(System.out::println);
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/612035
推荐阅读
相关标签
  

闽ICP备14008679号