1. Introduction

The Java Stream Api provides a number of useful apis that make it easy to convert collections or multiple elements of the same type into streams for operation. Today we’ll look at merging streams.

2. Merge streams

Stream merges only if the elements are of the same type.

2.1 the concat

The easiest way to merge streams is through the 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);
Copy the code

This merge is the concatenation of two streams one after the other:

2.2 Merging of multiple streams

Merging multiple streams We can also use the above method for “nesting operation” :

Stream.concat(Stream.concat(stream, another), more);
Copy the code

You can continue layer by layer, if there are too many streams to merge and it doesn’t look very clear.

The flatmap operation of a Stream is shown in the following figure:

So we can merge multiple streams using 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);
Copy the code

In this way, multiple streams are first used as elements to generate a Stream of type Stream

> and then flatmap tiling to merge.

2.3 Third-party Libraries

There are many third-party libraries StreamEx and Jooλ that can be combined. In addition, Reactor 3 can merge a Stream into a reaction Stream, which may be useful in some scenarios. Here’s a demonstration:

List<Integer> block = Flux.fromStream(stream)
                       .mergeWith(Flux.fromStream(another))
                                 .collectList()
                                 .block();
Copy the code

3. Summary

Merging streams is a common operation if you use the Java Stream Api regularly. Today’s brief introduction to merging streams will be useful to you. I am a small fat brother, a lot of attention! More dry goods were brought.

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn