Java Stream 流如何進行合並操作


1. 前言

Java Stream Api 提供了很多有用的 Api 讓我們很方便將集合或者多個同類型的元素轉換為流進行操作。今天我們來看看如何合並 Stream 流。

2. Stream 流的合並

Stream 流合並的前提是元素的類型能夠一致。

2.1 concat

最簡單合並流的方法是通過 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);

這種合並是將兩個流一前一后進行拼接:

2.2 多個流的合並

多個流的合並我們也可以使用上面的方式進行“套娃操作”:

Stream.concat(Stream.concat(stream, another), more);

你可以一層一層繼續套下去,如果需要合並的流多了,看上去不是很清晰。

我之前介紹過一個Stream 的 flatmap 操作 ,它的大致流程可以參考里面的這一張圖:

因此我們可以通過 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 平鋪操作合並。

2.3 第三方庫

有很多第三方的強化庫 StreamExJooλ 都可以進行合並操作。另外反應式編程庫 Reactor 3 也可以將 Stream 流合並為反應流,在某些場景下可能會有用。這里演示一下:

List<Integer> block = Flux.fromStream(stream)
                       .mergeWith(Flux.fromStream(another))
                                 .collectList()
                                 .block();

3. 總結

如果你經常使用 Java Stream Api ,合並 Stream 流是經常遇到的操作。今天簡單介紹了合並 Stream 流的方式,希望對你有用。我是 碼農小胖哥 ,多多關注!更多干貨奉上。

關注公眾號:Felordcn 獲取更多資訊

個人博客:https://felord.cn


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM