這篇文章將為大家詳細講解有關Java中怎么合并Stream流,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
成都創新互聯公司是專業的響水網站建設公司,響水接單;提供成都做網站、成都網站制作,網頁設計,網站設計,建網站,PHP網站建設等專業做網站服務;采用PHP框架,可快速的進行響水網站開發網頁制作和功能擴展;專業做搜索引擎喜愛的網站,專業的做網站團隊,希望更多企業前來合作!
Stream.concat()
靜態方法:
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);
這種合并是將兩個流一前一后進行拼接:
Stream.concat(Stream.concat(stream, another), more);
你可以一層一層繼續套下去,如果需要合并的流多了,看上去不是很清晰。
我之前介紹過一個Stream 的 flatmap 操作[2],它的大致流程可以參考里面的這一張圖:
flatmap
進行實現合并多個流:
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);
這種方式是先將多個流作為元素生成一個類型為
Stream<Stream<T>>
的流,然后進行
flatmap
平鋪操作合并。
List<Integer> block = Flux.fromStream(stream)
.mergeWith(Flux.fromStream(another))
.collectList()
.block();
關于Java中怎么合并Stream流就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
分享文章:Java中怎么合并Stream流
網站URL:http://m.newbst.com/article12/isgegc.html
成都網站建設公司_創新互聯,為您提供建站公司、微信小程序、Google、品牌網站建設、網站制作、搜索引擎優化
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯