赞
踩
目录
1.Stream关注的是对数据的运算,与CPU打交道
集合关注的是数据的存储,与内存打交道
2.注意
①Stream 自己不会存储元素
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
3.Stream 执行流程
①Stream的实例化
②一系列的中间操作(过滤、映射、...)
③终止操作
4.说明:
①一个中间操作链,对数据源的数据进行处理
②一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
Java8中的Collection接口被扩展,提供了两个获取流的方法:
- @Test
- public void test1() {//方式一:通过集合
- List<Employee> employees = Employee.getEmployees();
- //default Stream<E> stream():返回一个顺序流
- Stream<Employee> stream = employees.stream();
- //default Stream<E> parallelStream():返回一个并行流
- Stream<Employee> employeeStream = employees.parallelStream();
- }
Java8中的Arrays的静态方法stream()可以获取数组流:
重载形式,能够处理对应基本类型的数组:
- @Test
- public void test2() {//方式二:通过数组
- //public static IntStream stream(int[] array)
- //public static LongStream stream(long[] array)
- //public static DoubleStream stream(double[] array)
- int[] ints = new int[]{1, 2, 3, 4, 5, 6};
- IntStream intStream = Arrays.stream(ints);
- }
可以调用Stream类静态方法of(),通过显示值创建一个流。它可以接收任意数量的参数。
- @Test
- public void test3() {//方式三:通过Stream的of()
- //public static<T> Stream<T> of(T... values):返回一个流
- Stream<String> stringStream = Stream.of("tom", "小米", "小明");
-
- Employee[] employees = new Employee[]{new Employee("小红"), new Employee("小蓝")};
- Stream<Employee> employeeStream = Stream.of(employees);
- }
可以使用具体方法Stream.iterate()和Stream.generate(),创建无限流。
- @Test
- public void test4() {//方法四:创建无限流
- //迭代:public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)
- Stream.iterate(0, t -> t + 1).limit(10).forEach(System.out::println);
- //生成:public static<T> Stream<T> generate(Supplier<T> s)
- Stream.generate(Math::random).limit(10).forEach(System.out::println);
- }
代码使用案例:
- @Test
- public void test1() {
- List<Employee> list = Employee.getEmployees();
- //filter(Predicate p) --接收Lambda,从流中排除某些元素。
- Stream<Employee> stream = list.stream();
- stream.forEach(System.out::println);
- System.out.println();
- //注意stream对象已经不能再使用了!!!
-
- //练习:查询员工表中薪资大于10000的员工信息
- list.stream().filter(employee -> employee.getSalary() > 10000).forEach(System.out::println);
- System.out.println();
-
- //limit(n) --截断流,使其元素不超过给定数量
- list.stream().limit(2).forEach(System.out::println);
- System.out.println();
-
- //skip(n) --跳过n个元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回空流。
- //与limit(n)互补
- list.stream().skip(2).forEach(System.out::println);
- System.out.println();
-
- //distinct() --筛选,通过流所生成元素的hashCode()和equals()去除重复元素
- list.add(new Employee("Tom", 5000.0));
- list.add(new Employee("Tom", 5000.0));
- list.add(new Employee("Tom", 5000.0));
- list.stream().distinct().forEach(System.out::println);
- }
-
-
- //控制台输出如下
- Employee(name=小明, salary=9000.0)
- Employee(name=Tom, salary=10000.0)
- Employee(name=Daicy, salary=12000.0)
-
- Employee(name=Daicy, salary=12000.0)
-
- Employee(name=小明, salary=9000.0)
- Employee(name=Tom, salary=10000.0)
-
- Employee(name=Daicy, salary=12000.0)
-
- Employee(name=小明, salary=9000.0)
- Employee(name=Tom, salary=10000.0)
- Employee(name=Daicy, salary=12000.0)
- Employee(name=Tom, salary=5000.0)
-
- Process finished with exit code 0
代码使用案例:
- //映射
- @Test
- public void test2() {
- //map(Function f) --接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被
- List<String> list = Arrays.asList("aa", "cc", "bb", "dd");
- list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
- System.out.println();
-
- //练习1:获取员工姓名长度大于3的员工的姓名
- List<Employee> employeeList = Employee.getEmployees();
- employeeList.stream().map(employee -> employee.getName())
- .filter(name -> name.length() > 3).forEach(System.out::println);
- //我觉得可以不用map,实践对此题来说效果一样
- //employeeList.stream().filter(employee -> employee.getName().length() > 3)
- // .forEach(employee -> System.out.println(employee.getName()));
- System.out.println();
-
- //练习2:获取list集合中字符串中的每个字符
- Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest2::fromStringToStream);
- streamStream.forEach(s -> {
- s.forEach(System.out::println);
- });
- System.out.println();
- //flatMap(Function f) --接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流串连成一个流
- list.stream().flatMap(StreamAPITest2::fromStringToStream).forEach(System.out::println);
- }
-
- //将字符串中的多个字符构成的集合转换为对应的Stream的实例
- public static Stream<Character> fromStringToStream(String str) {//aa
- ArrayList<Character> list = new ArrayList<>();
- for (char c : str.toCharArray()) {
- list.add(c);
- }
- return list.stream();
- }
代码使用案例:
- //排序
- @Test
- public void test3() {
- //sorted() --自然排序
- List<Integer> list = Arrays.asList(12, 44, 75, 43, 88, 0, -23, 9, -67);
- list.stream().sorted().forEach(System.out::println);
- //抛异常,原因:Employee没有实现Comparable接口
- //Employee.getEmployeeList().stream().sorted().forEach(System.out::println);
- System.out.println();
-
- //sorted(Comparator com) --定制排序
- List<Employee> employeeList = Employee.getEmployeeList();
- employeeList.stream().sorted((e1, e2) -> {
- int ageValue = Integer.compare(e1.getAge(), e2.getAge());
- if (ageValue == 0) {//如果age相等,则根据salary从大到小排序
- return -Double.compare(e1.getSalary(), e2.getSalary());
- } else {
- return ageValue;
- }
- }).forEach(System.out::println);
- }
-
- //控制台输出
- -67
- -23
- 0
- 9
- 12
- 43
- 44
- 75
- 88
-
- Employee(name=小明, salary=9000.0, age=18)
- Employee(name=Daicy, salary=12000.0, age=25)
- Employee(name=Tom, salary=10000.0, age=25)
代码使用案例:
代码使用案例:
代码使用案例:
- //收集
- @Test
- public void test4() {
- //collect(Collector c) --将流转换为其他形式。
- // 接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
- //练习1:查找工资大于6000的员工,结果返回为一个List或Set
- List<Employee> employees = Employee.getEmployeeList();
- List<Employee> employeeList = employees.stream()
- .filter(emp -> emp.getSalary() > 6000).collect(Collectors.toList());
- Set<Employee> employeeSet = employees.stream()
- .filter(emp -> emp.getSalary() > 6000).collect(Collectors.toSet());
- employeeList.forEach(System.out::println);
- employeeSet.forEach(System.out::println);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。