flatMap的用法和含義住要通過一個案例來講解,

案例:對給定單詞列表 ["Hello","World"],你想返回列表["H","e","l","o","W","r","d"]
第一種方式
String[] words = new String[]{"Hello","World"};
List 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 類型的。你真正想要的是用Stream來表示一個字符串。
下方圖是上方代碼stream的運行流程
第二種方式:flatMap(對流扁平化處理)
String[] words = new String[]{"Hello","World"};
List 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運行流程,
//扁平化流
//找出數組中唯一的字符
String[] strArray = {"hello", "world"};
//具體實現
List res = Arrays.stream(strArray)
.map(w -> w.split(""))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
System.out.println(res);
//TODO 案例
System.out.println("--------------------------------");
//Demo1:給定數組,返回數組平方和(直接使用映射)
//[1,2,3,4]=>[1,4,9,16]
Integer[] nums1 = {1, 2, 3, 4};
List nums1List = Arrays.asList(nums1);
List res1 = nums1List.stream().map(i -> i * i).collect(Collectors.toList());
System.out.println(res1);
System.out.println("--------------------------------");
//Demo2:給定兩數組,返回數組對
//[1,2,3],[3,4]=>[1,3],[1,4],[2,3],[2,4],[3,3],[3,4]
Integer[] nums2 = {1, 2, 3};
Integer[] nums3 = {3, 4};無錫正規婦科 http://www.xasgyy.net/
List nums2List = Arrays.asList(nums2);
List nums3List = Arrays.asList(nums3);
//使用2個map嵌套過濾
List res2 = nums2List.stream().flatMap(i -> nums3List.stream().map(j -> new int[]{i, j})).collect(Collectors.toList());
System.out.println(res2.size());
System.out.println("--------------------------------");
//Demo3:針對Demo2和Demo1組合返回總和能被3整除的數對
//(2,4)和(3,3)是滿足條件的
List res3 = nums2List.stream().flatMap(i -> nums3List.stream().filter(j -> (i + j) % 3 == 0).map(j -> new int[]{i, j})).collect(Collectors.toList());
System.out.println(res3.size());
}
}
創新互聯www.cdcxhl.cn,專業提供香港、美國云服務器,動態BGP最優骨干路由自動選擇,持續穩定高效的網絡助力業務部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統配攻擊溯源,準確進行流量調度,確保服務器高可用性。佳節活動現已開啟,新人活動云服務器買多久送多久。
新聞名稱:java8streamflatMap流的扁平化操作-創新互聯
分享地址:http://www.yijiale78.com/article0/dpsgio.html
成都網站建設公司_創新互聯,為您提供域名注冊、企業建站、移動網站建設、網站設計公司、App設計、小程序開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯