It's easy to combine two Stream objects.
In fact, it's so easy I'll show you how to do it in this very brief guide.
So without further ado, let's get started.
A Simple Use Case
Let's make this easy.
Suppose you've got two (2) List objects with first names of people.
Crank up some test data that looks like this:
List<String> names1 = List.of("Joe", "Betty", "Bobby"); List<String> names2 = List.of("Franklin", "Slim");
Now you can easily convert those to Stream objects thanks to the stream() method.
But then you'll have two (2) Stream objects and not one (1) Stream object that contains everything. You want just a single object.
The solution is to use the concat() method.
A Cool concat()
Here's how that method works:
Stream<String> both = Stream.concat(names1.stream(), names2.stream());
As you can see from above, concat() is a static method. You don't need to instatiate anything to use it.
But you can't just combine names1 and names2 as they aren't streams. So you have to call the stream() method for each list.
Now that's going to give you a new Stream object with all the elements from both of the original streams.
At that point, you can handle it just like you'd handle any other stream. If you want to just view its contents, run code that looks like this:
both.forEach(name -> System.err.println(name));
That will give you this output:
Joe Betty Bobby Franklin Slim
As you can see, the concat() method not only combined the streams, but also preserved the orders from the original lists. That's a nice bonus.
Another bonus: if either of the input streams is parallel, then the resulting stream is parallel.
Unfortunately, you can only combine two streams with concat(). It's not one of those methods that lets you add as many objects as you want.
If you want to combine more than two streams, you'll need to run multiple concat() methods.
Still, that beats manually combining them.
You could also use Stream.of() to combine multiple streams and then invoke flatMap(). I might write an article about that one day.
But today is not that day.
Another thing to keep in mind: once you combine the two streams, updates or modifications to the original streams might not get reflected in the new stream.
However, I think you should avoid modifying the original streams once you've done the concatenation just to ensure data integrity. My $.02.
Wrapping It Up
There you have it: an easy way to combine a couple of streams.
Now take what you learned about here and start using it in your own code. You'll be glad you did.
Photo by from