來源於 https://blog.csdn.net/Mark_Chao/article/details/80810030
flatMap的用法和含義住要通過一個案例來講解,
案例:對給定單詞列表 ["Hello","World"],你想返回列表["H","e","l","o","W","r","d"]
第一種方式
-
String[] words = new String[]{"Hello","World"};
-
List<String[]> a = Arrays.stream(words)
-
.map(word -> word.split( ""))
-
.distinct()
-
.collect(toList());
-
a.forEach(System.out::print);
代碼輸出為:[Ljava.lang.String;@12edcd21[Ljava.lang.String;@34c45dca
(返回一個包含兩個String[]的list)
這個實現方式是由問題的,傳遞給map方法的lambda為每個單詞生成了一個String[](String列表)。因此,map返回的流實際上是Stream<String[]> 類型的。你真正想要的是用Stream<String>來表示一個字符串。
下方圖是上方代碼stream的運行流程
第二種方式:flatMap(對流扁平化處理)
-
String[] words = new String[]{"Hello","World"};
-
List<String> a = Arrays.stream(words)
-
.map(word -> word.split( ""))
-
.flatMap(Arrays::stream)
-
.distinct()
-
.collect(toList());
-
a.forEach(System.out::print);
結果輸出:HeloWrd
使用flatMap方法的效果是,各個數組並不是分別映射一個流,而是映射成流的內容,所有使用map(Array::stream)時生成的單個流被合並起來,即扁平化為一個流。
下圖是運用flatMap的stream運行流程,