This post will discuss how to add elements of a stream to an existing list in Java.

1. Using Collectors.toCollection() method

We can use a Collector to add elements to an existing list, as shown below:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
The above program violates the requirement of a supplier, as the supplier returns an existing list each time it is called, instead of a new, empty list.

If a supplier that returns the same list is passed to Collectors#toCollection(), each thread of parallel stream doesn’t get its own list for intermediate accumulation and appends its results to the specified list instead. So above code will fail if the stream is run in parallel.

 
One workaround is to call the sequential() on the stream before accumulating:

2. Using Stream.forEachOrdered() with List.add() method

We can add elements of a stream to an existing collection by using forEachOrdered() along with a method reference to List#add().

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
This approach works for sequential and parallel streams, but it does not benefit from concurrency as the method reference passed to forEachOrdered() will always be executed sequentially.

3. Using List.addAll() method + Collectors

We have seen that we can fill a list by repeatedly calling the add() method on every element of the stream. But instead of calling add() every time, a better approach is to replace it with a single call the addAll() method, as shown below. This approach, however, creates an intermediate list.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

4. Using Stream.concat() method + Collectors

This approach doesn’t mutate the original list but creates a new list containing elements from the specified stream and original list.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

That’s all about adding elements of a Stream into an existing List in Java.