Java中的流式编程

基本介绍
  1. Stream是Java 8提供的新功能,是对集合对象功能的增强,能对集合对象进行各种非常便利、高效的聚合操作,或大批量数据操作
  2. 与Lambda表达式结合,可以提高编程效率、简洁性和程序可读性
  3. 它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用fork/join并行方式来拆分任务和加速处理过程
  4. 使用Stream API无需编写一行多线程的代码,就可以很方便地写出高性能的并发程序
特点
  1. Stream自己不会存储元素
  2. Stream的操作不会改变源对象,相反,他们会返回一个持有结果的新Stream
  3. Stream操作是延迟执行的,它会等到需要结果的时候才执行,也就是执行终端操作的时候
操作步骤
  1. 创建Stream,从集合、数组中获取一个流
  2. 中间操作链,对数据进行处理
  3. 终端操作,用来执行中间操作链,返回结果
创建Stream
  1. 将集合作为数据源,读取集合中的数据到一个流中

    	Stream<Integer> stream = list.parallelStream(); // 读取集合中的数据,将其读取到并行流中
    
  2. 将数组作为数据源,读取数组中的数据到一个流中

    	Stream<Integer> stream = Arrays.stream(array);  // 读取数组中的数据,将其读取到流中
    
  3. 使用静态方法Stream.of(),通过显式值创建一个流

    	Stream<Integer> stream = Stream.of(0, 1, 3, 5, 7, 9);
    
  4. 由函数创建,创建无限流

        // 注意:使用无限流一定要配合limit截断,不然会无限制创建下去
        Stream.generate(Math::random).limit(5).forEach(System.out::print); // 生成
        List<Integer> collect = Stream.iterate(0,i -> i + 1).limit(5).collect(Collectors.toList()); // 迭代
    
中间操作
  1. 数据准备

        public static Stream<Student> getDataSource() {
            List<Student> list = new ArrayList<>(); // 实例化一个集合,存Student对象
            Collections.addAll(list, new Student("xiaoming",17,90), ... ); // 添加若干数据
            return list.stream(); // 读取数据源,得到Stream对象
        }
        Stream<Student> dataSource = getDataSource(); // 获取数据源
    
  2. filter条件过滤,以将流中满足指定条件的数据保留,去掉不满足指定条件的数据

        dataSource.filter(s -> s.getScore() >= 60).forEach(System.out::println); // 过滤掉集合中成绩不及格的学生信息
    
  3. distinct去重,去除流中的重复的数据,这个方法是没有参数的,去重的规则与hashSet相同

        dataSource.distinct().forEach(System.out::println); // 去重
    
  4. sorted排序,将流中的数据,按照其对应的类实现的Comparable接口提供的比较规则进行排序

        dataSource.sorted((s1,s2) -> s1.age - s2.age).forEach(System.out::println); // 对流中的数据按照自定义的规则进行排序
    
  5. limit & skip

        // limit限制,表示截取流中的指定数量的数据(从第0开始),丢弃剩余部分
        // skip跳过,表示跳过指定数量的数据,截取剩余部分
        dataSource.sorted((s1,s2) -> s2.score - s1.score).distinct() // 获取成绩的[3,5]名
                .limit(5)
                .skip(2)
                .forEach(System.out::println);
    
  6. map元素映射,提供一个映射规则,将流中的每一个元素替换成指定的元素

        dataSource.map(s -> s.getName()).forEach(System.out::println);  // 获取所有学生的名字
        dataSource.map(Student::getScore).forEach(System.out::println); // 获取所有学生的成绩
        IntSummaryStatistics intSummaryStatistics = dataSource.mapToInt(Student::getScore).summaryStatistics(); // 统计成绩
        System.out.println(intSummaryStatistics.getMax());
        System.out.println(intSummaryStatistics.getMin());
        System.out.println(intSummaryStatistics.getAverage());
    
  7. flatMap扁平化映射,可以将流中的容器中的数据,直接读取到流中

        // 一般是用在map映射完成后,流中的数据是一个容器,而我们需要再对容器中的数据进行处理,此时使用扁平化映射
        Stream<String> stream = Arrays.stream(s);  // 将字符串数组中的数据读取到流中
        stream.map(e -> e.split("")) // 统计字符串数组中所有出现的字符
                .flatMap(Arrays::stream)
                .distinct()
                .forEach(System.out::print);
    
最终操作
  1. 数据准备

        public static Stream<Integer> getDataSource() {
            List<Integer> datasource = new ArrayList<>(); //  准备一个容器
            Collections.addAll(datasource,0,1,2,3,4,5,6,7,8,9); // 向容器中添加数据
            return datasource.stream(); // 读取数据源中的数据,得到Stream对象并返回
        }
        Stream<Integer> dataSource = getDataSource(); // 获取数据源
    
  2. collect将流中的数据整合起来

        // 最常见的处理是,读取流中的数据,整合到一个容器中,得到一个集合最终操作过后,会关闭流
        List<Integer> collect = dataSource.collect(Collectors.toList());
        Set<Integer> collect = dataSource.collect(Collectors.toSet());
        Map<Integer, String> collect = dataSource.collect(Collectors.toMap(i -> i + 1, i -> i.toString()));
    
  3. reduce将流中的数据按照一定的规则聚合起来

        Integer sum = dataSource.reduce((p1, p2) -> p1 + p2).get();
        Integer sum = dataSource.reduce(Integer::sum).get(); // 使用了方法引用,效果同上
        Integer sum = dataSource.reduce(new BinaryOperator<Integer>() { // 这是一个java 8之前复杂的匿名内部类写法,效果同上
            @Override
            public Integer apply(Integer integer, Integer integer2) {
                return integer + integer2;
            }
        }).get();
    
  4. count统计流中的数据数量

        long count = dataSource.count();
    
  5. forEach遍历流中数据

    	dataSource.forEach(System.out::println);
    
  6. max & min

        // max: 按照指定的对象比较规则,进行大小的比较,得出流中最大的数据
        // min: 按照指定的对象比较规则,进行大小的比较,得出流中最小的数据
        Integer integer = dataSource.max(Integer::compareTo).get(); // 获取流的最大值
        Integer integer = dataSource.min(Integer::compareTo).get(); // 获取流的最小值
    
  7. allMatch & anyMatch & noneMatch

        // allMatch: 只有当流中所有的元素都匹配指定的规则,才会返回true
        // anyMatch: 只要流中的任意数据满足指定的规则,就会返回true
        // noneMatch: 只有当流中所有的元素都不满足指定的规则,才会返回true
        boolean b = dataSource.allMatch(e -> e > 0);  // 所有数据都大于0则返回true,否则返回false
        boolean b = dataSource.anyMatch(e -> e > 8);  // 存在大于8的数据则返回true,否则返回false
        boolean b = dataSource.noneMatch(e -> e > 9); // 没有一条数据大于9,则返回true,否则返回false
    
  8. findFirst & findAny

        // findFirst
        //     * 获取流中的一个元素,获取的是流中的首元素
        //     * 在进行元素获取的时候,无论是串行流还是并行流,获取的都是首元素
        // findAny
        //     * 获取流中的一个元素,通常是首元素,但在并行流中,获取的可能不是首元素
        //     * 在进行元素获取的时候,串行流一定获取到的是流中的首元素,并行流获取到的可能是首元素,也可能不是
        ArrayList<Integer> datasource = new ArrayList<>();
        Collections.addAll(datasource,0,1,2,3,4,5);
        Integer integer = datasource.parallelStream().findFirst().get();
        Integer integer = datasource.parallelStream().findAny().get();
    
  9. IntStream

        int[] array = new int[] {0,1,2,3,4,5};   // 准备一个int数组,作为数据源
        IntStream stream = Arrays.stream(array); // 读取数据到流中,获取IntStream对象
        IntSummaryStatistics intSummaryStatistics = stream.summaryStatistics(); // 获取一个对流中数据的分析结果
        System.out.println("max = " + intSummaryStatistics.getMax());           // 获取最大值
        System.out.println("min = " + intSummaryStatistics.getMin());           // 获取最小值
        System.out.println("sum = " + intSummaryStatistics.getSum());           // 获取数据和
        System.out.println("average = " + intSummaryStatistics.getAverage());   // 获取平均值
        System.out.println("count = " + intSummaryStatistics.getCount());       // 获取数据的数量
    

你可能感兴趣的:(后端,java,后端)