• 6、终止Stream流


    1、终止操作

    这是Stream操作中的最后一步,终止操作,终止操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:ListIntegervoid

    2、查找与匹配

    2.1、方法介绍

    方法名 介绍 返回类型
    allMatch 检查是否匹配所有元素 boolean
    anyMatch 检查是否至少匹配一个元素 boolean
    noneMatch 检查是否没有匹配所有元素 boolean
    findFirst 返回第一个元素 Optional
    findAny 返回当前流中的任意元素 Optional
    count 返回流中元素总个数
    max 返回流中最大值
    min 返回流中最小值

    2.2、代码示例

    package java8;
    
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    /**
     * @Description:
     * @Date: 2020/7/15 00:04
     * @Auther: zhaodi
     */
    public class StreamDemo01 {
    
        public static void main(String[] args) {
            List<Student> studentList = new ArrayList<>();
            studentList.add(new Student(1, "赵迪", 23));
            studentList.add(new Student(3, "tom", 25));
            studentList.add(new Student(2, "tom", 27));
            studentList.add(new Student(2, "rose", 22));
    
            Comparator<Student> comparator = Comparator.comparingInt(Student::getId);
            List<Student> list = studentList.stream().sorted(comparator).collect(Collectors.toList());
            System.out.println(list);
    
            Boolean success = list.stream().allMatch(x -> x.getId() > 1);
            System.out.println(success); // false
    
            Boolean success1 = list.stream().anyMatch(x -> x.getId() > 2);
            System.out.println(success1); // true
    
            Boolean success2 = list.stream().noneMatch(x -> x.getId() == 2);
            System.out.println(success2);//false
            Optional<Student> op = list.stream().sorted(comparator).findFirst();
            Student student = op.get();
            System.out.println(student);
    
            Optional<Student> optional = list.stream().findAny();
    
            long count = list.stream().count();
            System.out.println(count);
    
            Optional<Student> opMax = list.stream().max(comparator);
    
            Optional<Student> opMin = list.stream().min(comparator);
    
        }
    }
    
    

    3、归约(reduce)

    3.1、方法介绍

    方法名 介绍 返回类型
    reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个Optional对象 Option
    reduce(T iden,BinaryOperator b) 可以将流中元素反复结合起来,得到一个值 T

    3.2、代码示例

    reduce方法非常的通用,后面介绍的countsum等都可以使用其实现。reduce方法有三个重载的方法,本文介绍两个最常用的,最后一个留给读者自己学习。先来看reduce方法的第一种形式,其方法定义如下

    第一种

    
        Optional<T> reduce(BinaryOperator<T> accumulator);
    
    
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Optional<Integer> optional= list.stream().reduce((x, y) -> x + y);
        System.out.println(optional.get()); // 45
    
    
    • 解释

    可以看到reduce方法接受一个函数,这个函数有两个参数,第一个参数是上次函数执行的返回值(也称为中间结果),第二个参数是stream中的元素,这个函数把这两个值相加,得到的和会被赋值给下次执行这个函数的第一个参数。要注意的是:第一次执行的时候第一个参数的值是Stream的第一个元素,第二个参数是Stream的第二个元素。这个方法返回值类型是Optional,这是Java8防止出现NPE的一种可行方法,后面的文章会详细介绍,这里就简单的认为是一个容器,其中可能会包含0个或者1个对象

    第二种

    T reduce(T identity, BinaryOperator<T> accumulator);
    
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer sum = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(sum);
    
    • 解释

    这个定义上上面已经介绍过的基本一致,不同的是:它允许用户提供一个循环计算的初始值,如果Stream为空,就直接返回该值。而且这个方法不会返回Optional,因为其不会出现null

    如上面代码所示:

    如果list集合里面没有一个对象的话,那么第一种写法会报错,第二种结果则是0

    备注

    mapreduce的连接通常称为map-reduce模式,例如

            List<Student> studentList = new ArrayList<>();
            studentList.add(new Student(1, "赵迪", 23));
            studentList.add(new Student(3, "tom", 25));
            studentList.add(new Student(2, "tom", 27));
            studentList.add(new Student(2, "rose", 22));
            Optional sum = studentList.stream().map(x -> x.getAge()).reduce((x, y) -> x + y);
    

    4、收集(collect)

    4.1、方法介绍

    方法名 介绍 返回类型
    collect(Collector c) 将流转换为其它形式。接受一个Collector接口的实现,用于给Stream中元素做汇总方法

    Collector接口中的方法的实现决定了如何对流执行收集操作(如收集到ListSetMap)。

    但是Collectors实现类提供了很多静态方法,可以方便的创建常见收集器实例,具体方法和实例如下

    方法名 介绍 返回类型
    Collectors.toList() 将流转换为List集合 List<T>
    Collectors.toSet() 将流转换为Set集合 Set<T>
    Collectors.toCollection(LinkedList::new) 将流转换为集合
    Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r) 转为Map,具体见下面代码 Map<String,Object>
    Collectors.counting() 统计个数 Long
    Collectors.averagingDouble(Student::getAge) 求平均值 Double
    Collectors.summingInt(Student::getAge) 求和 Integer
    Collectors.maxBy(Comparator c) 最大值 Optional<T>
    Collectors.minBy(Comparator c) 最小值 Optional<T>
    Collectors.groupingBy(Student::getName) 单个分组 Map<String,List<T>
    Collectors.partitioningBy(x->x.getAge()>26) 分区 Map<Boolean>,List<T>
    Collectors.summarizingDouble(Student::getAge) 统计分析 DoubleSummaryStatistics

    4.2、代码示例

    package java8;
    
    import java.util.*;
    import java.util.stream.Collectors;
    
    /**
     * @Description:
     * @Date: 2020/7/15 00:04
     * @Auther: zhaodi
     */
    public class StreamDemo01 {
    
        public static void main(String[] args) {
            List<Student> studentList = new ArrayList<>();
            studentList.add(new Student(1, "赵迪", 23));
            studentList.add(new Student(3, "tom", 25));
            studentList.add(new Student(2, "tom", 27));
            studentList.add(new Student(2, "rose", 22));
    
        
            // 转List
            List<Student> newList = studentList.stream().filter(x -> x.getAge() > 23).collect(Collectors.toList());
            System.out.println(newList); //[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)]
    
            // 转Set
            Set<Student> studentSet = studentList.stream().collect(Collectors.toSet());
            System.out.println(studentSet);//[Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22), Student(id=1, name=赵迪, age=23), Student(id=2, name=tom, age=27)]
    
            // 转集合
            studentList.stream().collect(Collectors.toCollection(LinkedList::new));
    
            // 转Map(e:旧的key,r:新的key,如果存在key重复,则使用新的key或者旧的key都可以)
            Map<String, Object> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r));
            System.out.println(studentMap); // {tom=27, 赵迪=23, rose=22}
    
            // 求个数
            Long count = studentList.stream().collect(Collectors.counting());
            System.out.println(count);
    
            // 平均值
            Double avgAge = studentList.stream().collect(Collectors.averagingDouble(Student::getAge));
            System.out.println(avgAge);
    
            // 求和
            Integer ageSum = studentList.stream().collect(Collectors.summingInt(Student::getAge));
            System.out.println(ageSum);
    
            // 最大值
            Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge);
            Optional<Student> maxStu = studentList.stream().collect(Collectors.maxBy(ageComparator));
            System.out.println(maxStu.get());
    
            // 最小值
            Optional<Integer> min = studentList.stream().map(Student::getAge).collect(Collectors.minBy(Integer::compare));
            System.out.println(min.get());
    
            // 单个分组(根据姓名分组)
            Map<String, List<Student>> stringListMap = studentList.stream().collect(Collectors.groupingBy(Student::getName));
            System.out.println(stringListMap);//{tom=[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)], 赵迪=[Student(id=1, name=赵迪, age=23)], rose=[Student(id=2, name=rose, age=22)]}
    
            // 多级分组(先根据姓名分,在根据年纪分)
            Map<String, Map<Object, List<Student>>> map = studentList.stream().collect(Collectors.groupingBy(Student::getName, Collectors.groupingBy((x) -> {
                if (x.getAge() > 26) {
                    return "老年";
                } else {
                    return "青年";
                }
            })));
            System.out.println(map);//{tom={青年=[Student(id=3, name=tom, age=25)], 老年=[Student(id=2, name=tom, age=27)]}, 赵迪={青年=[Student(id=1, name=赵迪, age=23)]}, rose={青年=[Student(id=2, name=rose, age=22)]}}
    
            // 分区(分为两个区,年纪大于26和小于等于26)
            Map<Boolean,List<Student>> partitionStudent = studentList.stream().collect(Collectors.partitioningBy(x->x.getAge()>26));
            System.out.println(partitionStudent); //{false=[Student(id=1, name=赵迪, age=23), Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22)], true=[Student(id=2, name=tom, age=27)]}
    
            // 统计分析
            DoubleSummaryStatistics dss = studentList.stream().collect(Collectors.summarizingDouble(Student::getAge));
            System.out.println(dss.getAverage());
            System.out.println(dss.getSum());
            System.out.println(dss.getMax());
    
            // 连接
    
            String  names = studentList.stream().map(Student::getName).collect(Collectors.joining(","));
            System.out.println(names); //赵迪,tom,tom,rose
    
    
        }
    }
    
    一个小小的程序员
  • 相关阅读:
    XSS之防御与绕过
    说说XXE漏洞那些事
    常见web中间件漏洞(五)weblogic漏洞
    DLL劫持漏洞
    常见web中间件漏洞(四)Tomcat漏洞
    常见web中间件漏洞(三)Nginx漏洞
    CNVD-2021-14536 锐捷 RG-UAC 统一上网行为管理审计系统信息泄露漏洞
    Jupyter安装并设置反向搭理
    读书-刑罚的历史
    读书-反常识
  • 原文地址:https://www.cnblogs.com/zhaod/p/13437179.html
Copyright © 2020-2023  润新知