Java8 之Stream 詳解

一. 什麼是Stream

​ Stream是數據渠道,是用於操作數據源(集合、數組等)所生成的元素序列。集合講的是數據,流講的是計算

​ Stream有幾個值得注意的地方:

​ ①:Stream自己不會存儲元素

​ ②:Stream不會改變源對象。相反,它會返回一個持有結果的新Stream。

​ ③:Stream操作是延遲的,它會等到需要結果的時候才執行。

二. Stream操作三步驟

1. 創建Stream

​ 通過一個數據源(集合、數組)得到一個流

2. 中間操作

​ 一箇中間操作鏈,對數據源的數據進行處理

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

​ 一個終止操作,執行中間操作鏈併產生結果

三. Stream 的創建

Stream的創建基本上可以說有四種方法:

  1. 可以通過Collection系列集合提供的stream() 或者 parallelStream()

  2. 通過Arrays中的靜態方法stream()獲取數組流

  3. 通過Stream類中的靜態of()方法

  4. 創建無限流

    “`

      /**
      * 創建Stream
      */
     @Test
     public void test1(){
    
         //1. 可以通過Collection系列集合提供的stream() 或者 parallelStream()
    
         Stream<String> stream1 = list.stream();
    
         //2. 通過Arrays中的靜態方法stream()獲取數組流
         String[] strArray = new String[10];
         Stream<String> stream2 = Arrays.stream(strArray);
    
         //3. 通過Stream類中的靜態of()方法
         Stream<String> stream3 =  Stream.of("aa","bb","cc");
    
         //4. 創建無限流
         //迭代
         Stream<Integer> stream4 = Stream.iterate(0,x -> x*2);
         //生成器
         Stream<Double> stream5 = Stream.generate(Math::random);
     }
    

    “`

四.Stream的中間操作

1.篩選與切片

​ ①:filter — 接收lambda,從流中排除某些元素

​ ②:limit — 截斷流,使其元素不超過給定數量

​ ③:skip — 跳過元素,返回一個扔掉了前n個元素的流。若流中元素不足n個,則返回空流。

​ ④:distinct — 篩選,通過流所生成元素的hashCode()和equals()方法除重複元素

    /**
     * filter、limit、skip、distinct 等篩選及切片操作
     */
    @Test
    public void test2(){
        // 中間操作 不會執行任何操作
        Stream<Student> stream1 = studentList.stream()
                                            .filter(student -> student.getAge()>22);

        // 終止操作 一次性執行全部內容 即"惰性求值"
        stream1.forEach(System.out::println);
//        Student{id=12, name='lisi', age=23}
//        Student{id=13, name='wangwu', age=24}
//        Student{id=14, name='zhaoliu', age=25}

        studentList.stream()
                .filter(student -> student.getAge()>22)
                .limit(2)
                .forEach(System.out::println);
//        Student{id=12, name='lisi', age=23}
//        Student{id=13, name='wangwu', age=24}

        studentList.stream()
                .filter(student -> student.getAge()>22)
                .skip(2)
                .forEach(System.out::println);
//        Student{id=14, name='zhaoliu', age=25}

        List<String> strList =Arrays.asList("aa","bb","cc","aa");
        strList.stream().distinct().forEach(System.out::println);
//        aa
//        bb
//        cc
    }
2.映射

​ ①:map — 接收一個函數作爲參數,該函數會作用到每個元素上,並將其映射成一個新元素

​ ②:flatMap — 接受一個函數作爲參數,將流中的每個值都換成另一個流,然後把所有的流連接成一個流

     /**
     * map、flatMap等映射操作
     */
    @Test
    public void test3(){
        List<String> strList =Arrays.asList("aa","bb","cc","aa");
        strList.stream().map(String::toUpperCase).forEach(System.out::print);
        // AABBCCAA
        studentList.stream().map(Student::getName).forEach(System.out::print);
        // zhangsanlisiwangwuzhaoliu

        // TestStream1 是方法所在的類名
        Stream<Stream<Character>> stream = strList.stream().map(TestStream1::toCharacter);
        stream.forEach(stre ->{
            stre.forEach(System.out::print);
        });
        // aabbccaa
        strList.stream().flatMap(TestStream1::toCharacter).forEach(System.out::print);
        // aabbccaa  此方法相當於上述操作的簡寫
    }

    private static Stream<Character> toCharacter(String str){
        List<Character> list =new ArrayList<>();
        for(Character chr : str.toCharArray()){
            list.add(chr);
        }
        return list.stream();
    }
3.排序

​ ①:sorted() — 產生一個新流,其中按自然順序排序

​ ②:sorted(Comparator com) — 產生一個新流,其中按比較器順序排序

    /**
     * sorted
     */
    @Test
    public void test4(){
        List<String> strList =Arrays.asList("bb","cc","aa");
        strList.stream().sorted().forEach(System.out::println);
        // aa
        // bb
        // cc
        studentList.stream().sorted(Comparator.comparing(Student::getName))
                                .forEach(System.out::println);
        //Student{id=12, name='lisi', age=23}
        //Student{id=13, name='wangwu', age=24}
        //Student{id=11, name='zhangsan', age=22}
        //Student{id=14, name='zhaoliu', age=25}
    }

五. Stream的終止操作

1. 查找與匹配

​ ①:allMatch(Predicate p) — 檢查是否匹配所有元素

​ ②:anyMatch(Predicate p) — 檢查是否至少匹配一個元素

​ ③:noneMatch(Predicate p) — 檢查是否沒有匹配所有元素

​ ④:findFirst() — 返回第一個元素

​ ⑤:findAny() — 返回當前流中的任意元素

​ ⑥:count() — 返回流中元素總數

​ ⑦: max(Comparator c) — 返回流中最大值

​ ⑧:min(Comparator c) — 返回流中最小值

​ ⑨:forEach(Consumer c) — 內部迭代

    @Test
    public void test5() {
        // 所有學生的年齡都是22歲嗎?
        boolean flag1 = studentList.stream().allMatch(s -> s.getAge() == 22);
        System.out.println(flag1); // false

        // 有學生的年齡是22歲嗎
        boolean flag2 = studentList.stream().anyMatch(s -> s.getAge() ==22);
        System.out.println(flag2); // true

        // 是不是沒有名字爲tom的學生
        boolean flag3 = studentList.stream().noneMatch(s -> s.getName().equals("tom"));
        System.out.println(flag3); // true

        // 得到集合中的第一個元素
        Optional<Student> op1 = studentList.stream().findFirst();
        System.out.println(op1.get()); // Student{id=11, name='zhangsan', age=22}

        // 得到集合中任一元素
        Optional<Student> op2 = studentList.stream().findAny();
        System.out.println(op2.get()); // Student{id=11, name='zhangsan', age=22}

        // 一共有幾個學生
        long count = studentList.stream().count();
        System.out.println(count);  // 4

        //得到年齡最大的學生信息
        Optional<Student> op3= studentList.stream().max(Comparator.comparing(Student::getAge));
        System.out.println(op3.get()); // Student{id=14, name='zhaoliu', age=25}

        //得到年齡最小的學生信息
        Optional<Student> op4= studentList.stream().min(Comparator.comparing(Student::getAge));
        System.out.println(op4.get());  // Student{id=11, name='zhangsan', age=22}
    }
2. 規約

​ ①:reduce(T identity, BinaryOperator accumulator) — identity爲初始值,將流中元素反覆結合起來,得到一個值。返回 T

​ ②:Optional reduce(BinaryOperator accumulator) — 將流中元素反覆結合起來,得到一個值。
返回 Optional

    @Test
    public void test6(){
        // 第一個reduce方法第一個參數代表賦予結果一個初始值,說明沒有空指針的危險 故直接返回基礎類型
        int age1 = studentList.stream().map(Student::getAge).reduce(0,(x, y) -> x+y);
        System.out.println(age1); // 94
        // 第二個reduce方法沒有初始值,爲了避免空指針的危險,故返回 Optional 類型
        Optional<Integer> age2 = studentList.stream().map(Student::getAge).reduce((x, y) -> x+y);
        System.out.println(age2.get()); // 94
    }   
3. 收集

​ ①: toList — 把流中元素收集到List

​ ②: toSet — 把流中元素收集到Set

​ ③: toCollection — 把流中元素收集到創建的集合

​ ④: counting — 計算流中元素的個數

​ ⑤:summingInt — 對流中元素的整數屬性求和

​ ⑥:averagingInt — 計算流中元素Integer屬性的平均值

​ ⑦:maxBy — 根據比較器選擇最大值

​ ⑧: minBy — 根據比較器選擇最小值

​ ⑨:joining — 連接流中每個字符串

​ ⑩:groupingBy — 根據某屬性值對流分組, 屬性爲K, 結果爲Map

    @Test
    public void test7(){
        // toList
        List<String> list = studentList.stream().map(Student::getName)
                                       .collect(Collectors.toList());
        list.forEach(System.out::print); //  zhangsanlisiwangwuzhaoliu
        System.out.println("------------------------------------");
        // toSet
        Set<String> set = studentList.stream().map(Student::getName)
                                    .collect(Collectors.toSet());
        set.forEach(System.out::print); // lisizhaoliuzhangsanwangwu
        System.out.println("------------------------------------");
        // toCollection
        HashSet<String> hashSet = studentList.stream().map(Student::getName)
                            .collect(Collectors.toCollection(HashSet::new));
        hashSet.forEach(System.out::print); // lisizhaoliuzhangsanwangwu
    }
    @Test
    public void test8(){
        // 總數
        long count = studentList.stream().collect(Collectors.counting());
        System.out.println(count);  // 4

        // 平均值
        double ave = studentList.stream().collect(Collectors.averagingInt(Student::getAge));
        System.out.println(ave);  // 23.5

        //總和
        int sum = studentList.stream().collect(Collectors.summingInt(Student::getAge));
        System.out.println(sum);  // 94

        //最大值
        Optional<Integer> max = studentList.stream().map(Student::getAge)
                                        .collect(Collectors.maxBy(Integer::compare));
        System.out.println(max.get());  // 25

        // 最小值
        Optional<Integer> min = studentList.stream().map(Student::getAge)
                .collect(Collectors.minBy(Integer::compare));
        System.out.println(min.get());  // 22

        // 分組
        Map<Integer,List<Student>> map = studentList.stream().collect(Collectors.
                                        groupingBy(Student::getAge));
        System.out.println(map);
        // {22=[Student{id=11, name='zhangsan', age=22}, Student{id=15, name='liuqi', age=22}],
        // 23=[Student{id=12, name='lisi', age=23}],
        // 24=[Student{id=13, name='wangwu', age=24}],
        // 25=[Student{id=14, name='zhaoliu', age=25}]}

        String str = studentList.stream().map(Student::getName)
                                .collect(Collectors.joining(","));
        System.out.println(str);  // zhangsan,lisi,wangwu,zhaoliu,liuqi
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章