Java Stream


一、Stream流介紹

1.1 集合處理數據的弊端

當我們需要對集合中的元素進行操作的時候,除了必需的添加、刪除、獲取外,最典型的就是集合遍歷。我們來體驗 集合操作數據的弊端,需求如下:

一個ArrayList集合中存儲有以下數據:

張無忌,周芷若,趙敏,張強,張三豐

需求:

1.拿到所有姓張的

2.拿到名字長度為3個字的

3.打印這些數據

代碼如下:

public static void main(String[] args) {
   // 一個ArrayList集合中存儲有以下數據:張無忌,周芷若,趙敏,張強,張三豐
   // 需求:1.拿到所有姓張的 2.拿到名字長度為3個字的 3.打印這些數據
   ArrayList<String> list = new ArrayList<>();
   Collections.addAll(list, "張無忌", "周芷若", "趙敏", "張強", "張三豐");
   // 1.拿到所有姓張的
   ArrayList<String> zhangList = new ArrayList<>(); // {"張無忌", "張強", "張三豐"}
   for (String name : list) {
    if (name.startsWith("張")) {
      zhangList.add(name);
    }
  }
   // 2.拿到名字長度為3個字的
   ArrayList<String> threeList = new ArrayList<>(); // {"張無忌", "張三豐"}
   for (String name : zhangList) {
     if (name.length() == 3) {
      threeList.add(name);
    }
   }
   // 3.打印這些數據
   for (String name : threeList) {
     System.out.println(name);
   }
}

循環遍歷的弊端

這段代碼中含有三個循環,每一個作用不同:

  1. 首先篩選所有姓張的人;
  2. 然后篩選名字有三個字的人;
  3. 最后進行對結果進行打印輸出。

每當我們需要對集合中的元素進行操作的時候,總是需要進行循環、循環、再循環。這是理所當然的么?不是。循環是做事情的方式,而不是目的。每個需求都要循環一次,還要搞一個新集合來裝數據,如果希望再次遍歷,只能再使 用另一個循環從頭開始。

那Stream能給我們帶來怎樣更加優雅的寫法呢?

Stream的更優寫法

下面來看一下借助Java 8的Stream API,修改后的代碼:

public class Demo03StreamFilter {
public static void main(String[] args) {
   List<String> list = new ArrayList<>();
       list.add("張無忌");
       list.add("周芷若");
       list.add("趙敏");
       list.add("張強");
       list.add("張三豐");
       list.stream()
           .filter(s -> s.startsWith("張"))
           .filter(s -> s.length() == 3)
           .forEach(System.out::println);
   }
}

直接閱讀代碼的字面意思即可完美展示無關邏輯方式的語義:獲取流、過濾姓張、過濾長度為3、逐一打印。我們真 正要做的事情內容被更好地體現在代碼中。

1.2 Stream流式思想概述

注意:Stream和IO流(InputStream/OutputStream)沒有任何關系,請暫時忘記對傳統IO流的固有印象!

Stream流式思想類似於工廠車間的“生產流水線”,Stream流不是一種數據結構,不保存數據,而是對數據進行加工 處理。Stream可以看作是流水線上的一個工序。在流水線上,通過多個工序讓一個原材料加工成一個商品。

image-20220402160126589

image-20220402160138379

Stream API能讓我們快速完成許多復雜的操作,如篩選、切片、映射、查找、去除重復,統計,匹配和歸約。

1.3 小結

首先我們了解了集合操作數據的弊端,每次都需要循環遍歷,還要創建新集合,很麻煩

Stream是流式思想,相當於工廠的流水線,對集合中的數據進行加工處理

二、獲取Stream流的兩種方式

獲取一個流非常簡單,有以下幾種常用的方式:

  • 所有的 Collection 集合都可以通過 stream 默認方法獲取流;
  • Stream 接口的靜態方法 of 可以獲取數組對應的流。

2.1 根據Collection獲取流

首先, java.util.Collection 接口中加入了default方法 stream 用來獲取流,所以其所有實現類均可獲取流。

public interface Collection {
    default Stream<E> stream()
}
import java.util.*;
import java.util.stream.Stream;
public class Demo04GetStream {
public static void main(String[] args) {
   // 集合獲取流
   // Collection接口中的方法: default Stream<E> stream() 獲取流
   List<String> list = new ArrayList<>();
   // ...
   Stream<String> stream1 = list.stream();
   Set<String> set = new HashSet<>();
   // ...
   Stream<String> stream2 = set.stream();
   Vector<String> vector = new Vector<>();
   // ...
   Stream<String> stream3 = vector.stream();
  }
}

java.util.Map 接口不是 Collection 的子接口,所以獲取對應的流需要分key、value或entry等情況:

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Demo05GetStream {
public static void main(String[] args) {
   // Map獲取流
   Map<String, String> map = new HashMap<>();
   // ...
   Stream<String> keyStream = map.keySet().stream();
   Stream<String> valueStream = map.values().stream();
   Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
  }
}

2.2 Stream中的靜態方法of獲取流

由於數組對象不可能添加默認方法,所以 Stream 接口中提供了靜態方法 of ,使用很簡單:

import java.util.stream.Stream;
public class Demo06GetStream {
public static void main(String[] args) {

   // Stream中的靜態方法: static Stream of(T... values)
   Stream<String> stream6 = Stream.of("aa", "bb", "cc");

   String[] arr = {"aa", "bb", "cc"};
   Stream<String> stream7 = Stream.of(arr);
   Integer[] arr2 = {11, 22, 33};

   Stream<Integer> stream8 = Stream.of(arr2);

   // 注意:基本數據類型的數組不行
   int[] arr3 = {11, 22, 33};
   Stream<int[]> stream9 = Stream.of(arr3);
  }
}

備注: of 方法的參數其實是一個可變參數,所以支持數組。

三、Stream常用方法和注意事項

3.1 Stream常用方法

Stream流模型的操作很豐富,這里介紹一些常用的API。這些方法可以被分成兩種:

image-20220402143233212

  • 終結方法:返回值類型不再是Stream 類型的方法,不再支持鏈式調用。本小節中,終結方法包括count 和forEach 方法。
  • 非終結方法:返回值類型仍然是Stream 類型的方法,支持鏈式調用。(除了終結方法外,其余方法均為非終結方法。)
  • 對比Spark的兩種算子

備注:本小節之外的更多方法,請自行參考API文檔。

3.2 Stream注意事項(重要)

  1. Stream只能操作一次
  2. Stream方法返回的是新的流
  3. Stream不調用終結方法,中間的操作不會執行

3.3 forEach方法

forEach 用來遍歷流中的數據

void forEach(Consumer<? super T> action);

該方法接收一個 Consumer 接口函數,會將每一個流元素交給該函數進行處理。例如:

@Test
public void testForEach() {

   List<String> one = new ArrayList<>();
   Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子");

   /*one.stream().forEach((String s) -> {
   System.out.println(s);
   });*/

   // 簡寫
   // one.stream().forEach(s -> System.out.println(s));
   one.stream().forEach(System.out::println);
}

3.4 count方法

Stream流提供 count 方法來統計其中的元素個數 :

long count();

該方法返回一個long值代表元素個數。基本使用:

@Test
public void testCount() {
   List<String> one = new ArrayList<>();
   Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子");
   System.out.println(one.stream().count());
}

3.5 filter方法

image-20220402150114668

filter用於過濾數據,返回符合過濾條件的數據

可以通過 filter 方法將一個流轉換成另一個子集流。方法聲明:

Stream<T> filter(Predicate<? super T> predicate);

該接口接收一個 Predicate 函數式接口參數(可以是一個Lambda或方法引用)作為篩選條件。

Stream流中的 filter 方法基本使用的代碼如:

@Test
public void testFilter() {

   List<String> one = new ArrayList<>();
   Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子");

   one.stream()
      .filter(s -> s.length() == 2)
      .forEach(System.out::println);
}

在這里通過Lambda表達式來指定了篩選的條件:姓名長度為2個字。

3.6 limit方法

image-20220402150105213

limit 方法可以對流進行截取,只取用前n個。方法簽名:

Stream<T> limit(long maxSize);

參數是一個long型,如果集合當前長度大於參數則進行截取。否則不進行操作。基本使用:

@Test
public void testLimit() {
List<String> one = new ArrayList<>();
   Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子");
   one.stream().limit(3).forEach(System.out::println);
}

3.7 skip方法

image-20220402150057942

如果希望跳過前幾個元素,可以使用 skip 方法獲取一個截取之后的新流:

Stream<T> skip(long n);

如果流的當前長度大於n,則跳過前n個;否則將會得到一個長度為0的空流。基本使用:

@Test
public void testSkip() {
   List<String> one = new ArrayList<>();
   Collections.addAll(one, "迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子");
   one.stream().skip(2).forEach(System.out::println);
}

3.8 map方法

image-20220402150046972

如果需要將流中的元素映射到另一個流中,可以使用 map 方法。方法簽名:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

該接口需要一個 Function 函數式接口參數,可以將當前流中的T類型數據轉換為另一種R類型的流。

Stream流中的 map 方法基本使用的代碼如:

@Test
public void testMap() {
   Stream<String> original = Stream.of("11", "22", "33");
   original.map(Integer::parseInt).forEach(System.out::println);
}

這段代碼中, map 方法的參數通過方法引用,將字符串類型轉換成為了int類型(並自動裝箱為 Integer 類對象)。

3.9 sorted方法

如果需要將數據排序,可以使用 sorted 方法。方法簽名:

Stream<T> sorted();
Stream<T> sorted(Comparator<? super T> comparator);

基本使用

Stream流中的 sorted 方法基本使用的代碼如:

@Test
public void testSorted() {
// sorted(): 根據元素的自然順序排序
// sorted(Comparator<? super T> comparator): 根據比較器指定的規則排序
   Stream.of(33, 22, 11, 55)
                           .sorted()
                           .sorted((o1, o2) -> o2 - o1)
                           .forEach(System.out::println);
}

這段代碼中, sorted 方法根據元素的自然順序排序,也可以指定比較器排序。

3.10 distinct方法

image-20220402150036113

如果需要去除重復數據,可以使用 distinct 方法。方法簽名:

Stream<T> distinct();

基本使用

Stream流中的 distinct 方法基本使用的代碼如:

@Test
public void testDistinct() {
   Stream.of(22, 33, 22, 11, 33)
       .distinct()
       .forEach(System.out::println);
}

如果是自定義類型如何是否也能去除重復的數據呢?

@Test
public void testDistinct2() {
Stream.of(
   new Person("劉德華", 58),
   new Person("張學友", 56),
   new Person("張學友", 56),
   new Person("黎明", 52))
   .distinct()
   .forEach(System.out::println);
}
public class Person {
   private String name;
   private int age;
   // 省略其他
}

自定義類型是根據對象的hashCode和equals來去除重復元素的。

3.11match方法

如果需要判斷數據是否匹配指定的條件,可以使用 Match 相關方法。方法簽名:

boolean allMatch(Predicate<? super T> predicate);
boolean anyMatch(Predicate<? super T> predicate);
boolean noneMatch(Predicate<? super T> predicate)

基本使用

Stream流中的 Match 相關方法基本使用的代碼如:

@Test
public void testMatch() {
boolean b = Stream.of(5, 3, 6, 1)
       // .allMatch(e -> e > 0); // allMatch: 元素是否全部滿足條件
       // .anyMatch(e -> e > 5); // anyMatch: 元素是否任意有一個滿足條件
       .noneMatch(e -> e < 0); // noneMatch: 元素是否全部不滿足條件
       System.out.println("b = " + b);
}

3.12 find方法

image-20220402150022523

如果需要找到某些數據,可以使用 find 相關方法。方法簽名:

Optional<T> findFirst();
Optional<T> findAny();

基本使用

Stream流中的 find 相關方法基本使用的代碼如:

@Test
public void testFind() {
       Optional<Integer> first = Stream.of(5, 3, 6, 1).findFirst();
       System.out.println("first = " + first.get());
       
       Optional<Integer> any = Stream.of(5, 3, 6, 1).findAny();
       System.out.println("any = " + any.get());
}

3.13 max和min方法

image-20220402150014938

如果需要獲取最大和最小值,可以使用 max 和 min 方法。方法簽名:

Optional<T> max(Comparator<? super T> comparator);
Optional<T> min(Comparator<? super T> comparator);

基本使用

Stream流中的 max 和 min 相關方法基本使用的代碼如:

@Test
public void testMax_Min() {
   Optional<Integer> max = Stream.of(5, 3, 6, 1).max((o1, o2) -> o1 - o2);
   System.out.println("first = " + max.get());

   Optional<Integer> min = Stream.of(5, 3, 6, 1).min((o1, o2) -> o1 - o2);
   System.out.println("any = " + min.get());
}

3.14 reduce方法

image-20220402150004800

如果需要將所有數據歸納得到一個數據,可以使用 reduce 方法。方法簽名:

T reduce(T identity, BinaryOperator<T> accumulator);

基本使用

Stream流中的 reduce 相關方法基本使用的代碼如:

@Test
public void testReduce() {
   int reduce = Stream.of(4, 5, 3, 9)
               .reduce(0, (a, b) -> {
                       System.out.println("a = " + a + ", b = " + b);return a + b;
               });
   // reduce:
   // 第一次將默認做賦值給x, 取出第一個元素賦值給y,進行操作
   // 第二次,將第一次的結果賦值給x, 取出二個元素賦值給y,進行操作
   // 第三次,將第二次的結果賦值給x, 取出三個元素賦值給y,進行操作
   // 第四次,將第三次的結果賦值給x, 取出四個元素賦值給y,進行操作
   System.out.println("reduce = " + reduce);
   // 化簡
   int reduce2 = Stream.of(4, 5, 3, 9)
                       .reduce(0, (x, y) -> {return Integer.sum(x, y);});
   // 進一步化簡
    int reduce3 = Stream.of(4, 5, 3, 9).reduce(0, Integer::sum);
    
   int max = Stream.of(4, 5, 3, 9)
                   .reduce(0, (x, y) -> {
                   return x > y ? x : y;
                  });
   System.out.println("max = " + max);

}

x = 0, y = 4
x = 4, y = 5
x = 9, y = 3
x = 12, y = 9
reduce = 21
max = 9

image-20220402150212388

3.15 map和reduce組合使用

@Test
public void testMapReduce() {
       // 求出所有年齡的總和
   int totalAge = Stream.of(
       new Person("劉德華", 58),
       new Person("張學友", 56),
       new Person("郭富城", 54),
       new Person("黎明", 52))
       .map((p) -> p.getAge())
       .reduce(0, (x, y) -> x + y);
   System.out.println("totalAge = " + totalAge);

   // 找出最大年齡
   int maxAge = Stream.of(
       new Person("劉德華", 58),
       new Person("張學友", 56),
       new Person("郭富城", 54),
    new Person("黎明", 52))
       .map((p) -> p.getAge())
       .reduce(0, (x, y) -> x > y ? x : y);
   System.out.println("maxAge = " + maxAge);

   // 統計 數字2 出現的次數
   int count = Stream.of(1, 2, 2, 1, 3, 2)
   .map(i -> {
       if (i == 2) {
         return 1;
       } else {
         return 0;
        }
       })
       .reduce(0, Integer::sum);
   System.out.println("count = " + count);
} 

3.16 mapToIn

image-20220402151304118

如果需要將Stream中的Integer類型數據轉成int類型,可以使用 mapToInt 方法。方法簽名:

IntStream mapToInt(ToIntFunction<? super T> mapper);

Stream流中的 mapToInt 相關方法基本使用的代碼如:

@Test
public void test1() {
   // Integer占用的內存比int多,在Stream流操作中會自動裝箱和拆箱
   Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5});
   // 把大於3的和打印出來
   // Integer result = stream
   // .filter(i -> i.intValue() > 3)

   // .reduce(0, Integer::sum);
   // System.out.println(result);
   // 先將流中的Integer數據轉成int,后續都是操作int類型
   IntStream intStream = stream.mapToInt(Integer::intValue);
   int reduce = intStream
           .filter(i -> i > 3)
           .reduce(0, Integer::sum);
       System.out.println(reduce);

   // 將IntStream轉化為Stream<Integer>
   IntStream intStream1 = IntStream.rangeClosed(1, 10);
   Stream<Integer> boxed = intStream1.boxed();
   boxed.forEach(s -> System.out.println(s.getClass() + ", " + s));
}

3.17 concat方法

如果有兩個流,希望合並成為一個流,那么可以使用 Stream 接口的靜態方法 concat :

static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

備注:這是一個靜態方法,與 java.lang.String 當中的 concat 方法是不同的。

該方法的基本使用代碼如:

@Test
public void testContact() {
   Stream<String> streamA = Stream.of("張三");
   Stream<String> streamB = Stream.of("李四");
   Stream<String> result = Stream.concat(streamA, streamB);
   result.forEach(System.out::println);
}

3.18 Stream綜合案例

現在有兩個 ArrayList 集合存儲隊伍當中的多個成員姓名,要求使用傳統的for循環(或增強for循環)依次進行以下 若干操作步驟:

  1. 第一個隊伍只要名字為3個字的成員姓名;
  2. 第一個隊伍篩選之后只要前3個人;
  3. 第二個隊伍只要姓張的成員姓名;
  4. 第二個隊伍篩選之后不要前2個人;
  5. 將兩個隊伍合並為一個隊伍;
  6. 根據姓名創建 Person 對象;
  7. 打印整個隊伍的Person對象信息。

兩個隊伍(集合)的代碼如下:

public class DemoArrayListNames {
public static void main(String[] args) {
       List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子", "洪七公");
       List<String> two = List.of("古力娜扎", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛","張三");
       // ....
       }
}

而 Person 類的代碼為:

public class Person {
   private String name;
   public Person() {}
    public Person(String name) {
    this.name = name;
   }
   @Override
   public String toString() {
    return "Person{name='" + name + "'}";
   }
   public String getName() {
    return name;
   }
   public void setName(String name) {
    this.name = name;
   }
}

傳統方式

使用for循環 , 示例代碼:

public class DemoArrayListNames {
    public static void main(String[] args) {
        List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子", "洪七公");
        List<String> two = List.of("古力娜扎", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛", "張三");

        // 第一個隊伍只要名字為3個字的成員姓名;
        List<String> oneA = new ArrayList<>();

        for (String name : one) {
            if (name.length() == 3) {
                oneA.add(name);
            }
        }

        // 第一個隊伍篩選之后只要前3個人;
        List<String> oneB = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            oneB.add(oneA.get(i));
        }

        // 第二個隊伍只要姓張的成員姓名;
        List<String> twoA = new ArrayList<>();
        for (String name : two) {
            if (name.startsWith("張")) {
                twoA.add(name);
            }
        }

        // 第二個隊伍篩選之后不要前2個人;
        List<String> twoB = new ArrayList<>();
        for (int i = 2; i < twoA.size(); i++) {
            twoB.add(twoA.get(i));
        }

        // 將兩個隊伍合並為一個隊伍;
        List<String> totalNames = new ArrayList<>();
        totalNames.addAll(oneB);
        totalNames.addAll(twoB);

        // 根據姓名創建Person對象;
        List<Person> totalPersonList = new ArrayList<>();
        for (String name : totalNames) {
            totalPersonList.add(new Person(name));
        }
        // 打印整個隊伍的Person對象信息。
        for (Person person : totalPersonList) {
            System.out.println(person);
        }

    }
}

運行結果為:

Person{name='宋遠橋'}
Person{name='蘇星河'}
Person{name='洪七公'}
Person{name='張二狗'}
Person{name='張天愛'}
Person{name='張三'}

Stream方式

等效的Stream流式處理代碼為:

public class DemoStreamNames {
    public static void main(String[] args) {
        List<String> one = List.of("迪麗熱巴", "宋遠橋", "蘇星河", "老子", "庄子", "孫子", "洪七公");
        List<String> two = List.of("古力娜扎", "張無忌", "張三豐", "趙麗穎", "張二狗", "張天愛", "張三");

        // 第一個隊伍只要名字為3個字的成員姓名;
        // 第一個隊伍篩選之后只要前3個人;
        Stream<String> streamOne = one.stream().filter(s -> s.length() == 3).limit(3);

        // 第二個隊伍只要姓張的成員姓名;
        // 第二個隊伍篩選之后不要前2個人;
        Stream<String> streamTwo = two.stream().filter(s -> s.startsWith("張")).skip(2);

        // 將兩個隊伍合並為一個隊伍;
        // 根據姓名創建Person對象;
        // 打印整個隊伍的Person對象信息。
        Stream.concat(streamOne, streamTwo).map(Person::new).forEach(System.out::println);

    }

}

運行效果完全一樣:

Person{name='宋遠橋'}
Person{name='蘇星河'}
Person{name='洪七公'}
Person{name='張二狗'}
Person{name='張天愛'}
Person{name='張三'}

四、收集Stream流中的結果

對流操作完成之后,如果需要將流的結果保存到數組或集合中,可以收集流中的數據

4.1 Stream流中的結果到集合中

Stream流提供 collect 方法,其參數需要一個 java.util.stream.Collector 接口對象來指定收集到哪 種集合中。java.util.stream.Collectors 類提供一些方法,可以作為 Collector`接口的實例:

public static Collector> toList() :轉換為 List 集合。

public static Collector> toSet() :轉換為 Set 集合。

下面是這兩個方法的基本使用代碼:

// 將流中數據收集到集合中

@Test
public void testStreamToCollection() {
Stream<String> stream = Stream.of("aa", "bb", "cc");
   // List<String> list = stream.collect(Collectors.toList());
   // Set<String> set = stream.collect(Collectors.toSet());
   ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
   HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
}

4.2 Stream流中的結果到數組中

Stream提供 toArray 方法來將結果放到一個數組中,返回值類型是Object[]的:

Object[] toArray();

其使用場景如:

@Test
public void testStreamToArray() {
   Stream<String> stream = Stream.of("aa", "bb", "cc");
   // Object[] objects = stream.toArray();
   // for (Object obj : objects) {
   // System.out.println();
   // }

   String[] strings = stream.toArray(String[]::new);
   for (String str : strings) {
     System.out.println(str);
   }
}

4.3 對流中數據進行聚合計算

當我們使用Stream流處理數據后,可以像數據庫的聚合函數一樣對某個字段進行操作。比如獲取最大值,獲取最小 值,求總和,平均值,統計數量。

@Test
public void testStreamToOther() {
   Stream<Student> studentStream = Stream.of(
                   new Student("趙麗穎", 58, 95),
                   new Student("楊穎", 56, 88),
                   new Student("迪麗熱巴", 56, 99),
                   new Student("柳岩", 52, 77));
   // 獲取最大值
    Optional<Student> collect = studentStream.collect(Collectors.maxBy((o1, o2) ->
    o1.getSocre() - o2.getSocre()));

   // 獲取最小值
    Optional<Student> collect = studentStream.collect(Collectors.minBy((o1, o2) ->
    o1.getSocre() - o2.getSocre()));
   // System.out.println(collect.get());

   // 求總和
    int sumAge = studentStream.collect(Collectors.summingInt(s -> s.getAge()));
    System.out.println("sumAge = " + sumAge);

   //平均值
    double avgScore = studentStream.collect(Collectors.averagingInt(s -> s.getSocre()));
    System.out.println("avgScore = " + avgScore);

   // 統計數量
    Long count = studentStream.collect(Collectors.counting());
    System.out.println("count = " + count);
}

4.4 對流中數據進行分組

當我們使用Stream流處理數據后,可以根據某個屬性將數據分組:

// 分組
@Test
public void testGroup() {
   Stream<Student> studentStream = Stream.of(
       new Student("趙麗穎", 52, 95),
       new Student("楊穎", 56, 88),
       new Student("迪麗熱巴", 56, 55),
       new Student("柳岩", 52, 33));
   // Map<Integer, List<Student>> map = studentStream.collect(Collectors.groupingBy(Student::getAge));

   // 將分數大於60的分為一組,小於60分成另一組
   Map<String, List<Student>> map = studentStream.collect(Collectors.groupingBy((s) ->{
           if (s.getSocre() > 60) {
             return "及格";
            }else {
             return "不及格";
            }
           }));
   map.forEach((k, v) -> {
         System.out.println(k + "::" + v);
      });
}

效果:

不及格::[Student{name='迪麗熱巴', age=56, socre=55}, Student{name='柳岩', age=52, socre=33}]
及格::[Student{name='趙麗穎', age=52, socre=95}, Student{name='楊穎', age=56, socre=88}]

4.5 對流中數據進行多級分組

還可以對數據進行多級分組:

// 多級分組
@Test
public void testCustomGroup() {
   Stream<Student> studentStream = Stream.of(
       new Student("趙麗穎", 52, 95),
       new Student("楊穎", 56, 88),
       new Student("迪麗熱巴", 56, 99),
       new Student("柳岩", 52, 77));
   Map<Integer, Map<String, List<Student>>> map =
   studentStream.collect(Collectors.groupingBy(s -> s.getAge(), Collectors.groupingBy(s -> {
           if (s.getSocre() >= 90) {
            return "優秀";
            } else if (s.getSocre() >= 80 && s.getSocre() < 90) {
            return "良好";
            } else if (s.getSocre() >= 80 && s.getSocre() < 80) {
            return "及格";
            } else {
            return "不及格";
            }
           })));

   map.forEach((k, v) -> {
     System.out.println(k + " == " + v);
   });
}

效果:

52 == {不及格=[Student{name='柳岩', age=52, socre=77}], 優秀=[Student{name='趙麗穎', age=52,
socre=95}]}
56 == {優秀=[Student{name='迪麗熱巴', age=56, socre=99}], 良好=[Student{name='楊穎', age=56,
socre=88}]}

4.6 對流中數據進行分區

image-20220402154356376

Collectors.partitioningBy 會根據值是否為true,把集合分割為兩個列表,一個true列表,一個false列表。

// 分區
@Test
public void testPartition() {
   Stream<Student> studentStream = Stream.of(
       new Student("趙麗穎", 52, 95),
       new Student("楊穎", 56, 88),
       new Student("迪麗熱巴", 56, 99),
       new Student("柳岩", 52, 77));
   // partitioningBy會根據值是否為true,把集合分割為兩個列表,一個true列表,一個false列表。
   Map<Boolean, List<Student>> map = studentStream.collect(Collectors.partitioningBy(s ->s.getSocre() > 90));

   map.forEach((k, v) -> {
     System.out.println(k + " == " + v);
   });
}

效果:

false == [Student{name='楊穎', age=56, socre=88}, Student{name='柳岩', age=52, socre=77}]
true == [Student{name='趙麗穎', age=52, socre=95}, Student{name='迪麗熱巴', age=56, socre=99}]

4.7 對流中數據進行拼接

// 拼接
@Test
public void testJoining() {
Stream<Student> studentStream = Stream.of(
   new Student("趙麗穎", 52, 95),
   new Student("楊穎", 56, 88),
   new Student("迪麗熱巴", 56, 99),
   new Student("柳岩", 52, 77));
   String collect = studentStream
           .map(Student::getName)
           .collect(Collectors.joining(">_<", "^_^", "^v^"));
   System.out.println(collect);
}

效果:

^_^趙麗穎>_<楊穎>_<迪麗熱巴>_<柳岩^v^

五、並行的Stream流

5.1 串行的Stream流

目前我們使用的Stream流是串行的,就是在一個線程上執行。

@Test
public void test0Serial() {
   long count = Stream.of(4, 5, 3, 9, 1, 2, 6)
           .filter(s -> {
                System.out.println(Thread.currentThread() + ", s = " + s);
               return true;
           })
           .count();

   System.out.println("count = " + count);
}

效果:

Thread[main,5,main], s = 4
Thread[main,5,main], s = 5
Thread[main,5,main], s = 3
Thread[main,5,main], s = 9
Thread[main,5,main], s = 1
Thread[main,5,main], s = 2
Thread[main,5,main], s = 6

5.2 並行的Stream流

parallelStream其實就是一個並行執行的流。它通過默認的ForkJoinPool,可能提高多線程任務的速度。

獲取並行Stream流的兩種方式

  1. 直接獲取並行的流
  2. 將串行流轉成並行流
@Test
public void testgetParallelStream() {
       ArrayList<Integer> list = new ArrayList<>();
       // 直接獲取並行的流
        Stream<Integer> stream = list.parallelStream();
       // 將串行流轉成並行流
       Stream<Integer> stream = list.stream().parallel();
}

並行操作代碼:

@Test
public void test0Parallel() {
   long count = Stream.of(4, 5, 3, 9, 1, 2, 6)
           .parallel() // 將流轉成並發流,Stream處理的時候將才去
           .filter(s -> {
             System.out.println(Thread.currentThread() + ", s = " + s);
            return true;
           })
           .count();
   System.out.println("count = " + count);
}

效果:

Thread[ForkJoinPool.commonPool-worker-13,5,main], s = 3
Thread[ForkJoinPool.commonPool-worker-19,5,main], s = 6
Thread[main,5,main], s = 1
Thread[ForkJoinPool.commonPool-worker-5,5,main], s = 5
Thread[ForkJoinPool.commonPool-worker-23,5,main], s = 4
Thread[ForkJoinPool.commonPool-worker-27,5,main], s = 2
Thread[ForkJoinPool.commonPool-worker-9,5,main], s = 9
count = 7 

5.3 並行和串行Stream流的效率對比

使用for循環,串行Stream流,並行Stream流來對5億個數字求和。看消耗的時間。

public class Demo06 {
private static long times = 50000000000L;
private long start;

   @Before
   public void init() {
    start = System.currentTimeMillis();
   }

   @After
   public void destory() {
       long end = System.currentTimeMillis();
       System.out.println("消耗時間: " + (end - start));

   }

   // 測試效率,parallelStream 120
   @Test
   public void parallelStream() {
       System.out.println("serialStream");
       LongStream.rangeClosed(0, times)
                   .parallel()
                   .reduce(0, Long::sum);
   }

   // 測試效率,普通Stream 342
   @Test
   public void serialStream() {
       System.out.println("serialStream");
       LongStream.rangeClosed(0, times)
        .reduce(0, Long::sum);
   }

   // 測試效率,正常for循環 421
   @Test
   public void forAdd() {
       System.out.println("forAdd");
       long result = 0L;
       for (long i = 1L; i < times; i++) {
         result += i;
       }
   }
}

我們可以看到parallelStream的效率是最高的。

Stream並行處理的過程會分而治之,也就是將一個大任務切分成多個小任務,這表示每個任務都是一個操作。

5.4 parallelStream線程安全問題

解決parallelStream線程安全問題

// 並行流注意事項
@Test
public void parallelStreamNotice() {

   ArrayList<Integer> list = new ArrayList<Integer>();
   for (int i = 0; i < 1000; i++) {
    list.add(i);
}

   List<Integer> newList = new ArrayList<>();
   // 使用並行的流往集合中添加數據
   list.parallelStream()
       .forEach(s -> {
         newList.add(s);
    });

   System.out.println("newList = " + newList.size());
}

運行效果:

newList = 903

我們明明是往集合中添加1000個元素,而實際上只有903個元素。

解決方法:

加鎖、使用線程安全的集合或者調用Stream的 toArray() / collect() 操作就是滿足線程安全的了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM