Java中怎么合并Stream流
这篇文章将为大家详细讲解有关Java中怎么合并Stream流,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1. 前言
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);
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 第三方库
List<Integer> block = Flux.fromStream(stream)
.mergeWith(Flux.fromStream(another))
.collectList()
.block();
关于Java中怎么合并Stream流就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。