当前位置: 首页 > 图灵资讯 > 技术篇> Java流式编程

Java流式编程

来源:图灵教育
时间:2024-03-10 16:20:12
基本介绍
  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. Streamm采用静态方法.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 Collector

下一篇:

java连接Mysql