1. 程式人生 > >一眼看穿flatMap和map的區別

一眼看穿flatMap和map的區別

ray replace list return add 控制臺 包含 ini ply

背景

map和flatmap,從字面意思或者官網介紹,可能會給一些人在理解上造成困擾【包括本人】,所以今天專門花時間來分析,現整理如下:

首先做一下名詞解釋------------------------------------------------

我的理解

map:map方法返回的是一個object,map將流中的當前元素替換為此返回值;

flatMap:flatMap方法返回的是一個stream,flatMap將流中的當前元素替換為此返回流拆解的流元素;

官方解釋

map:Returns a stream consisting of the results of applying the given function to the elements of this stream.

返回一個流,包含給定函數應用在流中每一個元素後的結果

flatmap:Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

返回一個流,包含將此流中的每個元素替換為通過給定函數映射應用於每個元素而生成的映射流的內容

舉例說明

有二箱雞蛋,每箱5個,現在要把雞蛋加工成煎蛋,然後分給學生。

map做的事情:把二箱雞蛋分別加工成煎蛋,還是放成原來的兩箱,分給2組學生;

flatMap做的事情:把二箱雞蛋分別加工成煎蛋,然後放到一起【10個煎蛋】,分給10個學生;

完整測試代碼如下:

 1 public class Map_FlatMap {
 2 
 3 
 4     List<String[]> eggs = new ArrayList<>();
 5 
 6     @Before
 7     public void init() {
 8         // 第一箱雞蛋
 9         eggs.add(new String[]{"雞蛋_1", "雞蛋_1", "雞蛋_1", "雞蛋_1", "雞蛋_1"});
10 // 第二箱雞蛋 11 eggs.add(new String[]{"雞蛋_2", "雞蛋_2", "雞蛋_2", "雞蛋_2", "雞蛋_2"}); 12 } 13 14 // 自增生成組編號 15 static int group = 1; 16 // 自增生成學生編號 17 static int student = 1; 18 19 /** 20 * 把二箱雞蛋分別加工成煎蛋,還是放在原來的兩箱,分給2組學生 21 */ 22 @Test 23 public void map() { 24 eggs.stream() 25 .map(x -> Arrays.stream(x).map(y -> y.replace("雞", "煎"))) 26 .forEach(x -> System.out.println("組" + group++ + ":" + Arrays.toString(x.toArray()))); 27 /* 28 控制臺打印:------------ 29 組1:[煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1] 30 組2:[煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2] 31 */ 32 } 33 34 /** 35 * 把二箱雞蛋分別加工成煎蛋,然後放到一起【10個煎蛋】,分給10個學生 36 */ 37 @Test 38 public void flatMap() { 39 eggs.stream() 40 .flatMap(x -> Arrays.stream(x).map(y -> y.replace("雞", "煎"))) 41 .forEach(x -> System.out.println("學生" + student++ + ":" + x)); 42 /* 43 控制臺打印:------------ 44 學生1:煎蛋_1 45 學生2:煎蛋_1 46 學生3:煎蛋_1 47 學生4:煎蛋_1 48 學生5:煎蛋_1 49 學生6:煎蛋_2 50 學生7:煎蛋_2 51 學生8:煎蛋_2 52 學生9:煎蛋_2 53 學生10:煎蛋_2 54 */ 55 } 56 57 }

一眼看穿flatMap和map的區別