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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章