天天看點

Java 8 流的使用詳解(Stream)

接着上一篇:Java 8 中的 Streams API 簡介

Stream 是對集合(Collection)對象功能的增強,它專注于對集合對象進行各種非常便利、高效的聚合操作(aggregate operation),或者大批量資料操作 (bulk data operation)。 

Stream的使用,會使代碼更加簡潔易讀;而且Java 8 的 Stream 使用并發模式,程式執行速度更快。

流的操作類型分兩種:

  • Intermediate :一個流可以後面跟随零個或多個 intermediate 操作。其目的主要是打開流,做出某種程度的資料映射/過濾,然後傳回一個新的流,交給下一個操作使用。這類操作都是惰性化的(lazy),就是說,僅僅調用到這類方法,并沒有真正開始流的周遊。
  • Terminal :一個流隻能有一個 terminal 操作,當這個操作執行後,流就被使用“光”了,無法再被操作。是以這必定是流的最後一個操作。Terminal 操作的執行,才會真正開始流的周遊,并且會生成一個結果,或者一個 side effect。

另外:還有一個類型可以描述 short-circuiting 是指:有時候需要在周遊中途停止周遊操作(即不繼續周遊下去,立即傳回值),比如查找第一個滿足條件的元素或者limit操作。

在Stream中short-circuiting操作有:anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit。

流的構造與轉換

# 下面提供最常見的幾種構造 Stream 的樣例:

// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();           

 ⚠️ 對于基本數值型,目前有三種對應的包裝類型 Stream:IntStream、LongStream、DoubleStream,他們的構造如下:

IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);           

# 下面提供最常見的幾種 轉換 的樣例:

// 1. Array
String[] strArray1 = stream.toArray(String[]::new);
// 2. Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
// 3. String
String str = stream.collect(Collectors.joining()).toString();           

 ⚠️ 一個 Stream 隻可以使用一次,上面的為了簡潔而重複使用了數次。

接下來,進入本篇的重點:

流的操作

當把一個資料結構包裝成 Stream 後,就要開始對裡面的元素進行各類操作了。常見的操作可以歸類如下:

  • Intermediate:
map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
  • Terminal:
forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator

下面看一下 Stream 的比較典型用法。

#1. map/flatMap

map:它的作用就是把 input Stream 的每一個元素,映射成 output Stream 的另外一個元素。
// 把所有的單詞轉換為大寫
List<String> output = wordList.stream()
                      .map(String::toUpperCase)
                      .collect(Collectors.toList());           
// 生成一個整數 list 的平方數 {1, 4, 9, 16}
List<Integer> nums = Arrays.asList(1, 2, 3, 4);
List<Integer> squareNums = nums.stream()
                           .map(n -> n * n)
                           .collect(Collectors.toList());           

從上面例子可以看出,map 生成的是個 1:1 映射,每個輸入元素,都按照規則轉換成為另外一個元素。還有一些場景,是一對多映射關系的,這時需要 flatMap。

Stream<List<Integer>> inputStream = Stream.of(
 Arrays.asList(1),
 Arrays.asList(2, 3),
 Arrays.asList(4, 5, 6)
 );
Stream<Integer> outputStream = inputStream.flatMap((childList) -> childList.stream());           
上面的 flatMap 把 input Stream 中的層級結構扁平化,就是将最底層元素抽出來放到一起,最終 output 的新 Stream 裡面已經沒有 List 了,都是直接的數字。

#2. filter

filter 對原始 Stream 進行某項測試,通過測試的元素被留下來生成一個新 Stream。
// 經過條件“被 2 整除”的 filter,剩下的數字為 {2, 4, 6}
Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens = Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);           
// 這段代碼首先把每行的單詞用 flatMap 整理到新的 Stream,然後保留長度不為 0 的,就是整篇文章中的全部單詞了
List<String> output = reader.lines()
                      .flatMap(line -> Stream.of(line.split(REGEXP)))
                      .filter(word -> word.length() > 0)
                      .collect(Collectors.toList());           

#3. forEach

forEach 方法接收一個 Lambda 表達式,然後在 Stream 的每一個元素上執行該表達式。
// Java 8
roster.stream()
      .filter(p -> p.getGender() == Person.Sex.MALE)
      .forEach(p -> System.out.println(p.getName()));

// Pre-Java 8
for (Person p : roster) {
    if (p.getGender() == Person.Sex.MALE) {
       System.out.println(p.getName());
    }
}           

以上代碼是對一個人員集合周遊,找出男性并列印姓名(forEach 和 pre-java8 的對比)。可以看出來,forEach 是為 Lambda 而設計的,保持了最緊湊的風格。而且 Lambda 表達式本身是可以重用的,非常友善。當需要為多核系統優化時,可以 parallelStream().forEach(),隻是此時原有元素的次序沒法保證,并行的情況下将改變串行時操作的行為,此時 forEach 本身的實作不需要調整,而 Java8 以前的 for 循環 code 可能需要加入額外的多線程邏輯。

但一般認為,forEach 和正常 for 循環的差異不涉及到性能,它們僅僅是函數式風格與傳統 Java 風格的差别。

⚠️ 另外一點需要注意,forEach 是 terminal 操作,是以它執行後,Stream 的元素就被”消費”掉了,你無法對一個 Stream 進行兩次 terminal 運算。下面的代碼是錯誤的:

stream.forEach(element -> doOneThing(element))
      .forEach(element -> doAnotherThing(element));           

相反,具有相似功能的 intermediate 操作 peek 可以達到上述目的。如下是出現在該 api javadoc 上的一個示例。

#4. peek

peek 對每個元素執行操作并傳回一個新的 Stream
Stream.of("one", "two", "three", "four")
      .filter(e -> e.length() > 3)
      .peek(e -> System.out.println("Filtered value: " + e))
      .map(String::toUpperCase)
      .peek(e -> System.out.println("Mapped value: " + e))
      .collect(Collectors.toList());           

⚠️ forEach 不能修改自己包含的本地變量值,也不能用 break/return 之類的關鍵字提前結束循環。

#5. findFirst

這是一個 termimal 兼 short-circuiting 操作,它總是傳回 Stream 的第一個元素,或者空。
Optional<Integer> firstInteger = Arrays.asList(3, 5, 7, 9, 11).stream().findFirst();
System.out.println(firstInteger.get()); 
Optional<String> firstString = Stream.of("one", "two", "three", "four").findFirst()
System.out.println(firstString.get());            

⚠️ 這裡比較重點的是它的傳回值類型:Optional,是以使用它需要盡可能避免 NullPointerException。

String strA = " abcd ", strB = null;
print(strA);
print("");
print(strB);
getLength(strA);
getLength("");
getLength(strB);
public static void print(String text) {
      // Java 8
      Optional.ofNullable(text).ifPresent(System.out::println);
      // Pre-Java 8
      if (text != null) {
         System.out.println(text);
      }
 }
public static int getLength(String text) {
      // Java 8
      return Optional.ofNullable(text).map(String::length).orElse(-1);
      // Pre-Java 8
      // return if (text != null) ? text.length() : -1;
 };           

在更複雜的 if (xx != null) 的情況中,使用 Optional 代碼的可讀性更好,而且它提供的是編譯時檢查,能極大的降低 NPE 這種 Runtime Exception 對程式的影響,或者迫使程式員更早的在編碼階段處理空值問題,而不是留到運作時再發現和調試。

Stream 中的 findAny、max/min、reduce 等方法等傳回 Optional 值。還有例如 IntStream.average() 傳回 OptionalDouble 等等。

#6. reduce

這個方法的主要作用是把 Stream 元素組合起來。它提供一個起始值(種子),然後依照運算規則(BinaryOperator),和前面 Stream 的第一個、第二個、第 n 個元素組合。從這個意義上說,字元串拼接、數值的 sum、min、max、average 都是特殊的 reduce。
// 字元串連接配接,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
// 求和,sumValue = 10, 有起始值
int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
// 求和,sumValue = 10, 無起始值
Optional<Integer> sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum);
// 過濾,字元串連接配接,concat = "ace"
concat = Stream.of("a", "B", "c", "D", "e", "F")
         .filter(x -> x.compareTo("Z") > 0)
         .reduce("", String::concat);           

上面代碼例如第一個示例的 reduce(),第一個參數(空白字元)即為起始值,第二個參數(String::concat)為 BinaryOperator。這類有起始值的 reduce() 都傳回具體的對象。而對于第四個示例沒有起始值的 reduce(),由于可能沒有足夠的元素,傳回的是 Optional,請留意這個差別。

#7. limit/skip 

limit 傳回 Stream 的前面 n 個元素;skip 則是扔掉前 n 個元素(它是由一個叫 subStream 的方法改名而來)。

 >>> limit 和 skip 對運作次數的影響

public void testLimitAndSkip() {
     List<Person> persons = new ArrayList();
     for (int i = 1; i <= 10000; i++) {
         Person person = new Person(i, "name" + i);
         persons.add(person);
     }
     List<String> personList2 = persons.stream()
            .map(Person::getName).limit(10).skip(3).collect(Collectors.toList());
     System.out.println(personList2);
}

private class Person {
     public int no;
     private String name;
     public Person (int no, String name) {
         this.no = no;
         this.name = name;
     }
     public String getName() {
          System.out.println(name);
          return name;
     }
}           

輸出結果為:

name1
name2
name3
name4
name5
name6
name7
name8
name9
name10
[name4, name5, name6, name7, name8, name9, name10]           

這是一個有 10,000 個元素的 Stream,但在 short-circuiting 操作 limit 和 skip 的作用下,管道中 map 操作指定的 getName() 方法的執行次數為 limit 所限定的 10 次,而最終傳回結果在跳過前 3 個元素後隻有後面 7 個傳回。

有一種情況是 limit/skip 無法達到 short-circuiting 目的的,就是把它們放在 Stream 的排序操作後,原因跟 sorted 這個 intermediate 操作有關:此時系統并不知道 Stream 排序後的次序如何,是以 sorted 中的操作看上去就像完全沒有被 limit 或者 skip 一樣。

>>> limit 和 skip 對 sorted 後的運作次數無影響

List<Person> persons = new ArrayList();
for (int i = 1; i <= 5; i++) {
    Person person = new Person(i, "name" + i);
    persons.add(person);
}
List<Person> personList2 = persons.stream()
                     .sorted((p1, p2) -> p1.getName().compareTo(p2.getName()))
                     .limit(2)
                     .collect(Collectors.toList());
System.out.println(personList2);           

上面的示例做了微調,首先對 5 個元素的 Stream 排序,然後進行 limit 操作。輸出結果為:

name2
name1
name3
name2
name4
name3
name5
name4
[[email protected], [email protected]]           

即雖然最後的傳回元素數量是 2,但整個管道中的 sorted 表達式執行次數沒有像前面例子相應減少。

⚠️ 最後有一點需要注意的是,對一個 parallel 的 Steam 管道來說,如果其元素是有序的,那麼 limit 操作的成本會比較大,因為它的傳回對象必須是前 n 個也有一樣次序的元素。取而代之的政策是取消元素間的次序,或者不要用 parallel Stream。

#8. sorted

對 Stream 的排序通過 sorted 進行,它比數組的排序更強之處在于你可以首先對 Stream 進行各類 map、filter、limit、skip 甚至 distinct 來減少元素數量後,再排序,這能幫助程式明顯縮短執行時間。

我們對上面示例進行優化:(排序前進行 limit 和 skip) 

List<Person> persons = new ArrayList();
for (int i = 1; i <= 5; i++) {
    Person person = new Person(i, "name" + i);
    persons.add(person);
}
List<Person> personList2 = persons.stream()
            .limit(2)
            .sorted((p1, p2) -> p1.getName().compareTo(p2.getName()))
            .collect(Collectors.toList());
System.out.println(personList2);           

結果會簡單很多:

name2
name1
[[email protected], [email protected]]           

當然,這種優化是有 business logic 上的局限性的:即不要求排序後再取值。

#9. min/max/distinct

min 和 max 的功能也可以通過對 Stream 元素先排序,再 findFirst 來實作,但前者的性能會更好,為 O(n),而 sorted 的成本是 O(n log n)。同時它們作為特殊的 reduce 方法被獨立出來也是因為求最大最小值是很常見的操作。
// 找出最長一行的長度
BufferedReader br = new BufferedReader(new FileReader("c:\\SUService.log"));
int longest = br.lines()
    .mapToInt(String::length)
    .max()
    .getAsInt();
br.close();
System.out.println(longest);           

下面的例子則使用 distinct 來找出不重複的單詞:

// 找出全文的單詞,轉小寫,并排序
List<String> words = br.lines()
             .flatMap(line -> Stream.of(line.split(" ")))
             .filter(word -> word.length() > 0)
             .map(String::toLowerCase)
             .distinct()
             .sorted()
             .collect(Collectors.toList());
br.close();
System.out.println(words);           

#10. Match

Stream 有三個 match 方法,從語義上說:
  • allMatch:Stream 中全部元素符合傳入的 predicate,傳回 true
  • anyMatch:Stream 中隻要有一個元素符合傳入的 predicate,傳回 true
  • noneMatch:Stream 中沒有一個元素符合傳入的 predicate,傳回 true
它們都不是要周遊全部元素才能傳回結果。例如 allMatch 隻要一個元素不滿足條件,就 skip 剩下的所有元素,傳回 false。

對上面示例的 Person 類稍做修改,加入一個 age 屬性和 getAge 方法:

List<Person> persons = new ArrayList();
persons.add(new Person(1, "name" + 1, 10));
persons.add(new Person(2, "name" + 2, 21));
persons.add(new Person(3, "name" + 3, 34));
persons.add(new Person(4, "name" + 4, 6));
persons.add(new Person(5, "name" + 5, 55));
boolean isAllAdult = persons.stream().allMatch(p -> p.getAge() > 18);
System.out.println("All are adult? " + isAllAdult);
boolean isThereAnyChild = persons.stream().anyMatch(p -> p.getAge() < 12);
System.out.println("Any child? " + isThereAnyChild);           

輸出結果:

All are adult? false
Any child? true           

>>>>>>>> Java 8 流的進階- 自己生成流(Stream)