• Stream API


    什么是Stream

    Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。

    使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

    流(Stream )是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。

    “集合讲的是数据,流讲的是计算! ”

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

    Stream操作的三个步骤

    1. 创建Stream

      一个数据源(如:集合、数组),获取一个流

    2. 中间操作

      一个中间操作链,对数据源的数据进行处理

    3. 终止操作( 终端操作)

      一个终止操作,执行中间操作链,并产生结果

    创建Stream的四种方式

    1. 通过 Collection 系列集合提供的 stream() 创建一个顺序流/串行流,或 parallelStream() 创建一个并行流。(关于并行流和串行流的详解,请参考:并行流与串行流

    2. 通过 Arrays 中的静态方法 stream() 获取数组流。

    3. 通过 Stream 类中的静态方法 of() 创建。

    4. 通过函数创建无限流。

    4.1 迭代

    4.2 生成

    示例:

        /**
         * 创建 Stream
         */
        @Test
        public void test1(){
            //1. 通过 Collection 系列集合提供的 stream() 创建一个顺序流,或 parallelStream() 创建一个并行流。
            List<String> list = new ArrayList<>();
            Stream<String> stream1 = list.stream();
            Stream<String> stream2 = list.parallelStream();
    
            //2. 通过 Arrays 中的静态方法 stream() 获取数组流。
            Stream<String> stream3 = Arrays.stream(new String[10]);
            Stream<Integer> stream4 = Arrays.stream(new Integer[]{1, 2});
            Stream<Employee> stream5 = Arrays.stream(new Employee[1]);
            //...
    
            //3. 通过 Stream 类中的静态方法 of() 创建。
            Stream<String> stream6 = Stream.of("a", "b", "c");
    
            //4. 通过函数创建无限流。
            //4.1 迭代
            Stream<Integer> stream7 = Stream.iterate(0, (x) -> x + 2);
            stream7.limit(10).forEach(System.out::println);
    
            //4.2 生成
            Stream<UUID> stream8 = Stream.generate(() -> UUID.randomUUID());
            stream8.limit(10).forEach(System.out::println);
        }
    View Code

    Stream的中间操作

    多个 中间操作 可以连接起来形成一个 流水线,除非流水线上触发终止操作,否则 中间操作不会执行任何的 处理!而在 终止操作时一次性全部 处理,称为“惰性求值”

    1. 筛选与切片

    方法 描述
    filter(Predicate p) 接收Lambda,从流中排出某些元素。
    distinct() 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    limit(long maxSize) 截断流,使其元素不超过给定数量
    skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流,若流中元素不足n个,则返回一个空流。与limit(n)互补

    示例:

    public class Employee {
        private String name;
        private Integer age;
        private Integer gender;
        private Double salary;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
        List<Employee> emps = Arrays.asList(
                new Employee("李四",  59,1, 6666.66),
                new Employee("张三",  18,1, 9999.99),
                new Employee("王五",  28,1, 3333.33),
                new Employee("赵六",  8, 0,7777.77),
                new Employee("赵六",  8, 0,7777.77),
                new Employee("赵六",  8, 0,7777.77),
                new Employee("田七",  38,0, 5555.55)
        );
        /**
         * 对 Stream 进行流水线式的中间操作
         */
        @Test
        public void test2(){
         /* 筛选与切片
            filter——接收 Lambda , 从流中排除某些元素。
            limit——截断流,使其元素不超过给定数量。
            skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
            distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
            */
            //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
            emps.stream().filter((e) -> e.getAge() > 20).forEach(System.out::println);
            System.out.println("---------------------------------------");
            emps.stream().filter((e) -> e.getSalary() > 5000).limit(2).forEach(System.out::println);
            System.out.println("---------------------------------------");
            emps.stream().filter((e) -> e.getSalary() > 5000).skip(2).forEach(System.out::println);
            System.out.println("---------------------------------------");
            emps.stream().distinct().forEach(System.out::println);//这里需要重写Employee对象的hashCode() 和 equals()方法才能去重成功
    
        }
    View Code

    2. 映射

    方法 描述
    map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
    mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
    mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
    flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

    示例:

        /**
         * 映射: map   ——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
         */
        @Test
        public void test3(){
            emps.stream() .map(Employee::getName).forEach(System.out::println);
            List<String> names = emps.stream().map(Employee::getName).collect(Collectors.toList());//提取emps 集合中的所有姓名,构成一个新的集合
            System.out.println(names);
            System.out.println("-------------------------------------------");
            List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
            strList.stream().map(String::toUpperCase).forEach(System.out::println);
    
        }
    
        /**
         * 映射:  flatMap ——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
         */
        @Test
        public void test4(){
            List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
    
            Stream<Stream<Character>> stream2 = strList.stream()
                    .map(TestStream1::filterCharacter);// map方法返回一个流,map中执行的方法本身又返回一个流,所以返回值就是 Stream<Stream<Character>> 结构
            stream2.forEach((sm) -> {
                sm.forEach(System.out::println);
            });
    
            System.out.println("---------------------------------------------");
    
            Stream<Character> stream3 = strList.stream()
                    .flatMap(TestStream1::filterCharacter);//flatMap 把所有的流连接成一个流
    
            stream3.forEach(System.out::println);
        }
    
        /**
         * 处理字符串,截取成每个字符构成的一个集合,返回这个字符集合的流
         * @param str
         * @return
         */
        public static Stream<Character> filterCharacter(String str){
            List<Character> list = new ArrayList<>();
            for (Character ch : str.toCharArray()) {
                list.add(ch);
            }
            return list.stream();
        }
    
    
        /**
         * 映射: mapToDouble,mapToInt,mapToLong
         */
        @Test
        public void test5(){
            //接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
            emps.stream().mapToDouble(Employee::getSalary).forEach(System.out::println);
            //接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
            emps.stream().mapToInt(Employee::getAge).forEach(System.out::println);
            //接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
            List<Long> longList = Arrays.asList(666L,777L,888L);
            longList.stream().mapToLong(Long::longValue).forEach(System.out::println);
        }
    View Code

    3. 排序

    方法 描述
    sorted() 产生一个新流,其中按自然顺序排序。
    sorted(Comparator comp) 产生一个新流,其中按比较器顺序排序。

    示例:

        /**
         * 排序:
         * sorted()——自然排序
         * sorted(Comparator com)——定制排序
         */
        @Test
        public void test6(){
            emps.stream()
                    .map(Employee::getSalary)
                    .sorted()
                    .forEach(System.out::println);
            System.out.println("------------------------------------");
            emps.stream()
                    .sorted((x, y) -> {
                        if(x.getAge() == y.getAge()){
                            return x.getName().compareTo(y.getName());
                        }else{
                            return Integer.compare(x.getAge(), y.getAge());
                        }
                    }).forEach(System.out::println);
        }
    View Code

    Stream的终止操作

    终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。

    1. 查找与匹配

    方法 描述
    allMatch(Predicate p) 检查是否匹配所有元素
    anyMatch(Predicate p) 检查是否至少匹配一个元素
    noneMatch(Predicate p) 检查是否没有匹配所有元素
    findFirst() 返回第一个元素
    findAny() 返回当前流中的任意元素
    count() 返回流中元素总数
    max(Comparator c) 返回流中最大值
    min(Comparator c) 返回流中最小值
    forEach(Consumer c) 内部迭代(使用Collection接口需要用户去做迭代,称为外部迭代。相反,StreamAPI使用内部迭代,帮你把迭代做了)

    示例:

    public class Employee {
        private String name;
        private Integer age;
        private Integer gender;
        private Double salary;
        private Status status;
    
        public enum Status {
            FREE, BUSY, VOCATION;
        }
    }
    ////////////////////////////////////////////////////////////////////////////////
    import org.junit.Test;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    
    public class TestStream2 {
    
        List<Employee> emps = Arrays.asList(
                new Employee("李四",  59,1, 6666.66, Employee.Status.VOCATION),
                new Employee("张三",  18,1, 9999.99, Employee.Status.BUSY),
                new Employee("王五",  28,1, 3333.33, Employee.Status.FREE),
                new Employee("赵六",  8, 0,7777.77, Employee.Status.BUSY),
                new Employee("赵六",  8, 0,7777.77, Employee.Status.FREE),
                new Employee("赵六",  8, 0,7777.77, Employee.Status.BUSY),
                new Employee("田七",  38,0, 5555.55, Employee.Status.VOCATION)
        );
    
        /**
         * 终止操作
         * allMatch——检查是否匹配所有元素
         * anyMatch——检查是否至少匹配一个元素
         * noneMatch——检查是否没有匹配的元素
         */
        @Test
        public void test1(){
            boolean bl = emps.stream()
                    .allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));//是否所有员工的状态都是 BUSY
            System.out.println(bl);
    
            boolean bl1 = emps.stream()
                    .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY)); //是否至少一个员工状态是 BUSY
            System.out.println(bl1);
    
            boolean bl2 = emps.stream()
                    .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY)); //是否没有员工的状态是 BUSY
            System.out.println(bl2);
        }
    
        /**
         * 终止操作
         * findFirst——返回第一个元素
         * findAny——返回当前流中的任意元素
         */
        @Test
        public void test2(){
            Optional<Employee> op = emps.stream()
                    .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
                    .findFirst();
            System.out.println(op.get());
    
            System.out.println("--------------------------------");
    
            Optional<Employee> op2 = emps.parallelStream()
                    .filter((e) -> e.getStatus().equals(Employee.Status.FREE))
                    .findAny();
            System.out.println(op2.get());
        }
        /**
         * 终止操作
         * count——返回流中元素的总个数
         * max——返回流中最大值
         * min——返回流中最小值
         */
        @Test
        public void test3(){
            long count = emps.stream()
                    .filter((e) -> e.getStatus().equals(Employee.Status.FREE))
                    .count();
            System.out.println(count);
    
            Optional<Double> op = emps.stream()
                    .map(Employee::getSalary)
                    .max(Double::compare);
            System.out.println(op.get());
    
            Optional<Employee> op2 = emps.stream()
                    .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
            System.out.println(op2.get());
        }
    
    
    }
    View Code

    2. 归约

    方法 描述
    reduce(T iden,BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回T
    reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>

    示例:

        /**
         * 归约
         * reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
         */
        @Test
        public void test1(){
            List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    
            Integer sum = list.stream()
                    .reduce(0, (x, y) -> x + y);
            //初始值为0,x 为上一次运算的结果,y 为当次传入的list集合中每个下标的值,然后得到一个最终的值
            /*
                第一次运算:初始值为 0 ,没有上一次运算的结果,所以 x = 0,y = list.get(0) => 1 , x + y 值为 1
                第二次运算:初始值为上一次运算的结果 1 ,所以 x = 1,y = list.get(1) => 2 , x + y 值为 3
                第三次运算:初始值为上一次运算的结果 3 ,所以 x = 3,y = list.get(2) => 3, x + y 值为 6
                第四次运算:初始值为上一次运算的结果 6 ,所以 x = 6,y = list.get(3) => 4, x + y 值为 10
                .......
                直到将 list 中的值全部拿来运算后,归约结束
             */
            System.out.println(sum);
    
            System.out.println("----------------------------------------");
    
            Optional<Double> op = emps.stream()
                    .map(Employee::getSalary)
                    .reduce(Double::sum);
    
            //这个道理同上,唯一不同的是,上面的归约结束返回的直接是一个运算结果,这里返回的是Optional对象
            //因为上面有初始值,那么运算后的结果一定不会为Null,下面的没有初始值,运算后的结果可能为Null,所以对于这种结果可能为Null的,就默认封装到Optional中去,就避免空指针
            System.out.println(op.get());
        }
    View Code

    备注:map 和 reduce 的连接通常称为 map-reduce 模式,比较常用。

    3. 收集

     方法 描述 
     collect(Collector c) 将流转换成其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法 

    示例:

        /**
         * 收集
         * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
         */
        @Test
        public void test2(){
            List<String> list = emps.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toList());//把emps集合中的所有员工姓名收集到list中
            list.forEach(System.out::println);
    
            System.out.println("----------------------------------");
    
            Set<String> set = emps.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toSet());//把emps集合中的所有员工姓名收集到set中
            set.forEach(System.out::println);
    
            System.out.println("----------------------------------");
    
            HashSet<String> hs = emps.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toCollection(HashSet::new));//把emps集合中的所有员工姓名收集到HashSet中
            hs.forEach(System.out::println);
    
        }
        /**
         * 收集
         * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
         */
        @Test
        public void test3(){
            Optional<Double> max = emps.stream()
                    .map(Employee::getSalary)//平均值
                    .collect(Collectors.maxBy(Double::compare));
            System.out.println(max.get());
    
            Optional<Employee> op = emps.stream()
                    .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));//最小值
            System.out.println(op.get());
    
            Double sum = emps.stream()
                    .collect(Collectors.summingDouble(Employee::getSalary));//
            System.out.println(sum);
    
            Double avg = emps.stream()
                    .collect(Collectors.averagingDouble(Employee::getSalary));//平均值
            System.out.println(avg);
    
            Long count = emps.stream()
                    .collect(Collectors.counting());//总数
            System.out.println(count);
    
            System.out.println("--------------------------------------------");
    
            DoubleSummaryStatistics dss = emps.stream()
                    .collect(Collectors.summarizingDouble(Employee::getSalary));
            System.out.println(dss.getMax());//获取最大值
            System.out.println(dss.getAverage());//平均值
            System.out.println(dss.getMin());//最小值
            System.out.println(dss.getCount());//总数
            System.out.println(dss.getSum());//
        }
    
        /**
         * 收集
         * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
         * 分组、多级分组
         */
        @Test
        public void test4(){
            //分组
            Map<Employee.Status, List<Employee>> map = emps.stream()
                    .collect(Collectors.groupingBy(Employee::getStatus));//按照状态分组
            System.out.println(map);
    
            System.out.println("--------------------------------------------");
            //多级分组
            Map<Employee.Status, Map<String, List<Employee>>> map1 = emps.stream()
                    .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
                        if(e.getAge() >= 60)
                            return "老年";
                        else if(e.getAge() >= 35)
                            return "中年";
                        else
                            return "成年";
                    })));//Collectors.groupingBy 中第二个参数接收的还是 Collectors.groupingBy,所以可以一层一层分组
    
            System.out.println(map1);
        }
    
        /**
         * 收集
         * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
         * 分区
         */
        @Test
        public void test5(){
            Map<Boolean, List<Employee>> map = emps.stream()
                    .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));//按照工资5000分区
    
            System.out.println(map);
        }
    
        /**
         * 收集
         * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
         * 连接
         */
        @Test
        public void test6(){
            String str = emps.stream()
                    .map(Employee::getName)
                    //.collect(Collectors.joining());//直接连接
                    //.collect(Collectors.joining("," ));//所有值连接中间用 , 隔开
                    .collect(Collectors.joining("," , "----", "===="));//所有值连接中间用 , 隔开;连接后的字符串添加前缀:"----"、后缀:"===="
    
            System.out.println(str);
        }
    View Code

     Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

     

    注意:流进行了终止操作后,不能再次使用

     备注:文中提到的 Optional ,详情请参考:Optional 容器类详情

  • 相关阅读:
    MySQL启动报错Starting MySQL. ERROR! The server quit without updating PID file
    vue安装
    web漏洞分析防御
    dedecms三级目录
    阿里云Linux服务器漏洞修复
    Windows下elasticsearch安装并且同步数据库
    解决ecshop清除缓存css样式没反应问题
    PHP正则匹配替换图片地址
    阿里云漏洞修复
    Apache Pig
  • 原文地址:https://www.cnblogs.com/y3blogs/p/13069021.html
Copyright © 2020-2023  润新知