
1. preface
Java Stream Api It provides many useful Apis that make it convenient for us to convert collections or multiple elements of the same type into streams for operation. Today we will look at how to merge Stream flow.
2. Merging of Stream streams
Stream The prerequisite for stream merging is that the types of elements can be consistent.
2.1 concat
The easiest way to merge streams is by Stream.concat()
Static method:
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);
This merge is to splice two streams one after the other:
2.2 Merging of multiple streams
For the merger of multiple streams, we can also use the above method to perform the "doll operation":
Stream.concat(Stream.concat(stream, another), more);
You can continue to cover it layer by layer. If there are too many streams that need to be merged, it won't look very clear.
I introduced one beforeflatmap operation of Stream , for its general process, you can refer to this picture inside:
So we can go through flatmap
Implement and merge multiple streams:
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);
This method is to first generate multiple streams as elements to generate a type of Stream<Stream<T>>
of the flow, and then proceed flatmap
Tiling operations merge.
2.3 third-party libraries
There are many third-party enhanced libraries StreamEx 、Jooλ Merge operations can be performed. In addition, reactive programming libraries Reactor 3 may be Stream Merging streams into reactive streams may be useful in some scenarios. Here's a demonstration:
List<Integer> block = Flux.fromStream(stream)
.mergeWith(Flux.fromStream(another))
.collectList()
.block();
3. summary
if you regularly use Java Stream Api , merge Stream Flow is a frequently encountered operation. Today we briefly introduced the merger Stream Flow method, I hope it will be useful to you.
Comments0