Java Stream Api 提供了不少有用的 Api 让咱们很方便将集合或者多个同类型的元素转换为流进行操做。今天咱们来看看如何合并 Stream 流。html
Stream 流合并的前提是元素的类型可以一致。java
最简单合并流的方法是经过 Stream.concat()
静态方法:react
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);
复制代码
这种合并是将两个流一前一后进行拼接:编程
多个流的合并咱们也可使用上面的方式进行“套娃操做”:api
Stream.concat(Stream.concat(stream, another), more);
复制代码
你能够一层一层继续套下去,若是须要合并的流多了,看上去不是很清晰。spa
我以前介绍过一个Stream 的 flatmap 操做 ,它的大体流程能够参考里面的这一张图:code
所以咱们能够经过 flatmap
进行实现合并多个流:cdn
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
平铺操做合并。htm
有不少第三方的强化库 StreamEx 、Jooλ 均可以进行合并操做。另外反应式编程库 Reactor 3 也能够将 Stream 流合并为反应流,在某些场景下可能会有用。这里演示一下:blog
List<Integer> block = Flux.fromStream(stream)
.mergeWith(Flux.fromStream(another))
.collectList()
.block();
复制代码
若是你常常使用 Java Stream Api ,合并 Stream 流是常常遇到的操做。今天简单介绍了合并 Stream 流的方式,但愿对你有用。我是 码农小胖哥 ,多多关注!更多干货奉上。
关注公众号:Felordcn获取更多资讯