Java Stream 流實(shí)現(xiàn)合并操作示例
本文實(shí)例講述了Java Stream 流實(shí)現(xiàn)合并操作。分享給大家供大家參考,具體如下:
1. 前言Java Stream Api 提供了很多有用的 Api 讓我們很方便將集合或者多個(gè)同類型的元素轉(zhuǎn)換為流進(jìn)行操作。今天我們來看看如何合并 Stream 流。
2. Stream 流的合并Stream 流合并的前提是元素的類型能夠一致。
2.1 concat最簡單合并流的方法是通過 Stream.concat() 靜態(tài)方法:
Stream<Integer> stream = Stream.of(1, 2, 3);Stream<Integer> another = Stream.of(4, 5, 6);Stream<Integer> concat = Stream.concat(stream, another);List<Integer> collect = concat.collect(Collectors.toList());List<Integer> expected = Lists.list(1, 2, 3, 4, 5, 6);Assertions.assertIterableEquals(expected, collect);
這種合并是將兩個(gè)流一前一后進(jìn)行拼接:
多個(gè)流的合并我們也可以使用上面的方式進(jìn)行“套娃操作”:
Stream.concat(Stream.concat(stream, another), more);
你可以一層一層繼續(xù)套下去,如果需要合并的流多了,看上去不是很清晰。
我之前介紹過一個(gè)Stream 的 flatmap 操作 ,它的大致流程可以參考里面的這一張圖:
因此我們可以通過 flatmap 進(jìn)行實(shí)現(xiàn)合并多個(gè)流:
Stream<Integer> stream = Stream.of(1, 2, 3);Stream<Integer> another = Stream.of(4, 5, 6);Stream<Integer> third = Stream.of(7, 8, 9);Stream<Integer> more = Stream.of(0);Stream<Integer> concat = Stream.of(stream,another,third,more). flatMap(integerStream -> integerStream);List<Integer> collect = concat.collect(Collectors.toList());List<Integer> expected = Lists.list(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);Assertions.assertIterableEquals(expected, collect);
這種方式是先將多個(gè)流作為元素生成一個(gè)類型為 Stream<Stream<T>> 的流,然后進(jìn)行 flatmap 平鋪操作合并。
2.3 第三方庫有很多第三方的強(qiáng)化庫 StreamEx 、Jooλ 都可以進(jìn)行合并操作。另外反應(yīng)式編程庫 Reactor 3 也可以將 Stream 流合并為反應(yīng)流,在某些場景下可能會(huì)有用。這里演示一下:
List<Integer> block = Flux.fromStream(stream) .mergeWith(Flux.fromStream(another)) .collectList() .block();3. 總結(jié)
如果你經(jīng)常使用 Java Stream Api ,合并 Stream 流是經(jīng)常遇到的操作。
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. python math模塊的基本使用教程2. 如何用python開發(fā)Zeroc Ice應(yīng)用3. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式4. python基于opencv批量生成驗(yàn)證碼的示例5. npm下載慢或下載失敗問題解決的三種方法6. ASP編碼必備的8條原則7. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法8. python用pyecharts實(shí)現(xiàn)地圖數(shù)據(jù)可視化9. python軟件測試Jmeter性能測試JDBC Request(結(jié)合數(shù)據(jù)庫)的使用詳解10. python uuid生成唯一id或str的最簡單案例
