Java8新特性之streamAPI(三)

stream操作的三个步骤之终止操作 

  • 查找与匹配
    * allMatch——检查是否匹配所有元素
    * anyMatch——检查是否至少匹配一个元素
    * noneMatch——检查是否没有匹配所有元素
    * findFirst——返回当前第一个元素
    * findAny——返回当前流中的任意元素
    * count——返回流中元素的总个数
    * max——返回流中最大值
    * min——返回流中最小值
  • 归约
    * 可将流中元素反复结合起来,得到一个值,返回T  /可以将流中元素反复结合起来,得到一个值,返回Optional<T>
    * reduce(T identity,BinaryOperator) / reduce(BinaryOperator)
  • 收集
    * collect——将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
    * Collect接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例
  • 分组、多级分组、分区
    package streamAPI;
    
    import lambda.Employee;
    import lambda.Employee.Status;
    import org.junit.Test;
    
    import java.util.*;
    import java.util.function.BinaryOperator;
    import java.util.stream.Collectors;
    
    
    /*
     *终止操作
     */
    public class TestStreamAPI3 {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 25, 9000, Status.FREE),
                new Employee("李四", 38, 10000, Status.BUSY),
                new Employee("王晓", 45, 12000, Status.FREE),
                new Employee("李华", 28, 9500, Status.FREE),
                new Employee("花花", 22, 8000, Status.VOCATION),
                new Employee("李华", 28, 9500, Status.VOCATION),
                new Employee("花花", 22, 8000, Status.BUSY),
                new Employee("花花", 22, 8000, Status.BUSY),
                new Employee("李华", 28, 9500, Status.BUSY),
                new Employee("花花", 22, 8000, Status.VOCATION)
        );
    
        /*
         *查找与匹配
         * allMatch——检查是否匹配所有元素
         * anyMatch——检查是否至少匹配一个元素
         * noneMatch——检查是否没有匹配所有元素
         * findFirst——返回当前第一个元素
         * findAny——返回当前流中的任意元素
         * count——返回流中元素的总个数
         * max——返回流中最大值
         * min——返回流中最小值
         */
        @Test
        public void test1() {
            boolean b1 = employees.stream()
                    .allMatch((e) -> e.getStatus().equals(Status.BUSY));
            System.out.println(b1);
    
            System.out.println("---------------------------------------");
    
            boolean b2 = employees.stream()
                    .anyMatch((e) -> e.getStatus().equals(Status.BUSY));
            System.out.println(b2);
    
            System.out.println("---------------------------------------");
    
            boolean b3 = employees.stream()
                    .noneMatch((e) -> e.getStatus().equals(Status.BUSY));
            System.out.println(b3);
    
            System.out.println("---------------------------------------");
    
            //返回最高薪资的记录
            Optional<Employee> op0 = employees.stream()
                    .sorted((e1, e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
                    .findFirst();
            System.out.println(op0.get());
    
            System.out.println("---------------------------------------");
    
            Optional<Employee> op1 = employees.stream()
                    .filter((e) -> e.getStatus().equals(Status.FREE))
                    .findAny();
            System.out.println(op1.get());
    
            System.out.println("---------------------------------------");
    
            Long count = employees.stream()
                    .count();
            System.out.println(count);
    
            System.out.println("---------------------------------------");
    
            Optional<Employee> op2 = employees.stream()
                    .max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
            System.out.println(op2.get());
    
            Optional<Employee> op3 = employees.stream()
                    .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
            System.out.println(op3.get());
    
            Optional<Double> op4 = employees.stream()
                    .map(Employee::getSalary)
                    .min(Double::compareTo);
            System.out.println(op4.get());
        }
    
        /*
         *归约
         * 可将流中元素反复结合起来,得到一个值,返回T  /可以将流中元素反复结合起来,得到一个值,返回Optional<T>
         * reduce(T identity,BinaryOperator) / reduce(BinaryOperator)
         */
        @Test
        public void test2() {
            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);
            System.out.println(sum);
    
            System.out.println("----------------------------------");
    
            Optional<Double> sum1 = employees.stream()
                    .map(Employee::getSalary)
                    .reduce(Double::sum);
            System.out.println(sum1.get());
        }
    
        /*
         *收集
         * collect——将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
         * Collect接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例
         */
        @Test
        public void test3() {
            List<String> list = employees.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toList());
            list.forEach(System.out::println);
    
            System.out.println("-------------------------------");
    
            Set<String> set = employees.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toSet());
            set.forEach(System.out::println);
    
            System.out.println("--------------------------------");
    
            HashSet<String> hs = employees.stream()
                    .map(Employee::getName)
                    .collect(Collectors.toCollection(HashSet::new));
            hs.forEach(System.out::println);
        }
    
        @Test
        public void test4() {
            //总数
            Long count = employees.stream()
                    .collect(Collectors.counting());
            System.out.println(count);
    
            System.out.println("--------------------------------");
    
            //平均值
            Double avg = employees.stream()
                    .collect(Collectors.averagingDouble(Employee::getSalary));
            System.out.println(avg);
    
            System.out.println("--------------------------------");
    
            //总和
            Double sum = employees.stream()
                    .collect(Collectors.summingDouble(Employee::getSalary));
            System.out.println(sum);
    
            //最大值员工
            Optional<Employee> max = employees.stream()
                    .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
            System.out.println(max.get());
    
            //最小值
            Optional<Double> min = employees.stream()
                    .map(Employee::getSalary)
                    .collect(Collectors.minBy(Double::compareTo));
    //                .collect(Collectors.minBy((e1, e2) -> Double.compare(e1, e2)));
            System.out.println(min.get());
        }
    
        //分组
        @Test
        public void test5() {
            Map<Status, List<Employee>> map = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getStatus));
            System.out.println(map);
        }
    
        //多级分组
        @Test
        public void test6() {
            Map<Status, Map<String, List<Employee>>> map = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
                        if (((Employee) e).getAge() <= 35) {
                            return "青年";
                        } else if (((Employee) e).getAge() <= 50) {
                            return "中年";
                        } else {
                            return "老年";
                        }
                    })));
            System.out.println(map);
        }
    
        //分区
        @Test
        public void test7() {
            Map<Boolean, List<Employee>> map = employees.stream()
                    .collect(Collectors.partitioningBy((e) -> e.getSalary() > 9000));
            System.out.println(map);
        }
    
    
        @Test
        public void test8() {
            DoubleSummaryStatistics dss = employees.stream()
                    .collect(Collectors.summarizingDouble(Employee::getSalary));
            System.out.println(dss.getSum());     //91500.0
            System.out.println(dss.getAverage());      //9150.0
            System.out.println(dss.getMax());      //12000.0
        }
    
        @Test
        public void test9() {
            String str = employees.stream()
                    .map(Employee::getName)
                    .collect(Collectors.joining(",","---","---"));
            System.out.println(str);       //---张三,李四,王晓,李华,花花,李华,花花,花花,李华,花花---
        }
    }
    

    相关函数声明详见:https://blog.csdn.net/qq_38358499/article/details/104636487

发布了111 篇原创文章 · 获赞 57 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_38358499/article/details/104642386

相关文章