Stream 相關的使用

說實話現在 寫stream 這博客有點 low 因爲現在的jdk 已經更新到11這樣了,而stream 卻是在 jdk8的時候被標註爲新特性,說實話習慣了 思維的定勢,但是好東西還是應該被拿出來分享,況且 stream的使用加速了代碼的創造。

Stream 的簡述:

Stream 是 Java8 中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執行非常複雜的查找、過濾和映射數據等操作。使用Stream API 對集合數據進行操作,就類似於使用 SQL 執行的數據庫查詢。也可以使用 Stream API 來並行執行操作。簡而言之,Stream API 提供了一種高效且易於使用的處理數據的方式。
特點:
         1 .不是數據結構,不會保存數據。
         2. 不會修改原來的數據源,它會將操作後的數據保存到另外一個對象中。(
         保留意見:畢竟peek方法可以修改流中元素)
         3. 惰性求值,流在中間處理過程中,只是對操作進行了記錄,並不會立即執行,
         需要等到執行終止操作的時候纔會進行實際的計算。
 咱們就開始一些具體的操作吧,jdk8有對應的說明文檔
filter:過濾流中的某些元素
limit(n):獲取n個元素
skip(n):跳過n元素,配合limit(n)可實現分頁
distinct:通過流中元素的 hashCode() 和 equals() 去除重複元素
sorted():自然排序,流中元素需實現Comparable接口
sorted(Comparator com):定製排序,自定義Comparator排序器  
peek:如同於map,能得到流中的每一個元素。但map接收的是一個Function表達式,
allMatch:接收一個 Predicate 函數,當流中每個元素都符合該斷言時才返回true,否則返回false
noneMatch:接收一個 Predicate 函數,當流中每個元素都不符合該斷言時才返回true,否則返回false
anyMatch:接收一個 Predicate 函數,只要流中有一個元素滿足該斷言則返回true,否則返回false
findFirst:返回流中第一個元素
findAny:返回流中的任意元素
count:返回流中元素的總個數
max:返回流中元素最大值
min:返回流中元素最小值

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        boolean allMatch = list.stream().allMatch(e -> e > 10); //false
        boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
        boolean anyMatch = list.stream().anyMatch(e -> e > 4);  //true

        Integer findFirst = list.stream().findFirst().get(); //1
        Integer findAny = list.stream().findAny().get(); //1

        long count = list.stream().count(); //5
        Integer max = list.stream().max(Integer::compareTo).get(); //5
        Integer min = list.stream().min(Integer::compareTo).get(); //1
        System.out.println("--"+allMatch+"----"+"noneMatch:"+noneMatch+"----"+"anyMatch:"+anyMatch+"----"+"findFirst:"+"----"+findFirst+"----"+"findAny:"+"----"+findAny+"----"
                +"count:"+"----"+count+"----"
                +"max:"+"----"+max+"----"+"min"+"----"+min);
Collector 相關操作
 Student s1 = new Student("aa", 10, 1);
        Student s2 = new Student("bb", 20, 2);
        Student s3 = new Student("cc", 10, 3);
        List<Student> list = Arrays.asList(s1, s2, s3);

        //裝成list
        List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
        ageList.forEach(System.out::println);
        //轉成set
        Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
        ageSet.forEach(System.out::println);
        //轉成map,注:key不能相同,否則報錯
        Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}

        //字符串分隔符連接
        String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)

       //聚合操作
       //1.學生總數
        Long count = list.stream().collect(Collectors.counting()); // 3
       //2.最大年齡 (最小的minBy同理)
        Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
       //3.所有人的年齡
        Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
       //4.平均年齡
        Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
       // 帶上以上所有方法
        DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
        System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());

       //分組
        Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
       //多重分組,先根據類型分再根據年齡分
        Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));

       //分區
       //分成兩部分,一部分大於10歲,一部分小於等於10歲
        Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));

       //規約
        Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40

交集/並集

 //庫裏面數據
 List<Integer> integerList= list.stream().map(對象::get對象屬性).collect(Collectors.toList());
//傳參數據
 List<Integer> typeList = Arrays.asList(typeIds);

 // 差集 (integerList - typeList) 
 List<Integer> reduce1 = integerList.stream().filter(item -> !typeList.contains(item)).collect(Collectors.toList());

 // 差集 (typeList - integerList) 
 List<Integer> reduce2 = typeList.stream().filter(item -> !integerList.contains(item)).collect(Collectors.toList());
 
//交集
List<String> intersection = integerList.stream().filter(item -> typeList .contains(item)).collect(toList());

//並集就是普通的add  

//去重並集

List<String> listAllDistinct = intersection.stream().distinct().collect(toList());

大概使用到的就這些

 

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