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);

这种合并是将两个流一前一后进行拼接:

[图片上传失败...(image-6d7d2c-1650020384157)]

2.2 多个流的合并

多个流的合并我们也可以使用上面的方式进行“套娃操作”:

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

你可以一层一层继续套下去,如果需要合并的流多了,看上去不是很清晰。

它的大致流程可以参考里面的这一张图:

[图片上传失败...(image-2874ba-1650020384157)]

因此我们可以通过 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 流的方式,希望对你有用。

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系
可以进交流群124388967获取,最后祝大家都能拿到自己心仪的offer

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值