Introduction
This post quickly explains how to join two lists using streams. I also show how to join two lists without using streams but with the list instances.
Using streams.concat()
The easiest way to join two lists with Streams is by using the Stream.concat(Stream a, Stream b)
method. The method takes two
Stream instances as parameters and puts the second Stream behind the first Stream. The result is a new list of strings with the content of both lists.
|
|
Using Stream.of()
We can also use Stream.of()
to join two lists, but then we need an extra step to get a single list of strings.
The result of Stream.of()
is a list with lists. So we need to call .flatMap(Collection::stream)
to map it to a single list of strings.
|
|
Using an ArrayList instance
The simplest way to add two lists is with the .addAll()
method. This method adds the elements of one list to another one.
The result is that the list instance calling the .addAll()
method now contains the elements of both lists.
|
|
Conclusion
In this post, we saw three ways to join lists in Java. We used the .concat()
and Stream.of().flatMap(Collection::stream)
methods to create a single
lists using streams. We also used an instance of ArrayList to add elements of another list to itself.