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 多个流的合并
多个流的合并我们也可以使用上面的方式进行“套娃操作”: