This post will discuss how to convert a stream to a list in Java.

1. Using Collectors class

We can collect elements of a stream in a container using the Stream.collect() method, which accepts a collector. We can pass collector returned by Collectors.toList() that accumulates the elements of the stream into a new list. This is the standard way to convert the stream to a list in Java 8 and above.

 
But Collectors.toList() doesn’t guarantee the type of the list returned. To have more control over the returned list, we can use the Collectors.toCollection() method to accept a constructor reference to the desired list.

2. Using Divide & Conquer

We can easily divide the problem into two parts:

  1. Convert stream to an array
  2. Convert array back to a list

The following program demonstrates it:

3. Using forEach() method

We can also loop through all elements of the stream using the forEach() method and use list.add() to add each element to an empty List.

 
Please note that if stream is parallel, elements may not be processed in original order with the forEach() method. We can use the forEachOrdered() method to preserve the original order, as shown below:

That’s all about converting Stream to a List in Java.