Convert Stream to List in Java: Five ways

In this Convert Stream to List in Java post, we show you various ways to convert a stream to a list in Java 8. This is one of the common problem while working with Stream API. E.g. when you are processing a List using Stream’s map and filter method, you want to get the result in some collection for sure to do other processing.

Here are 5 simple ways to convert Stream to List in Java. We introduce to convert a Stream of String to a List of String, then you can do converting a Stream of Integer to List of Integer and so on by yourself.

1. Using Collectors.toList() method
This is the normal way to collect the result of stream in a container in List and you can collect to Set or any Collection as well.

2. Using Collectors.toCollection() method
We can collect elements of Stream in any Collection, including ArrayList, LinkedList and other List as well. In this example, we are collecting Stream elements into ArrayList via interface method ArrayList::new.

3. Using forEach() method
Going through all element of Stream one by one and add them into a new List or ArrayList.

4. Using forEachOrdered method
Here we are using Parallel stream and this is extension of 3rd way. I noticed that elements of parallel stream be processed out of order. So we want to keep order of elements in Stream we must use forEachOrdered() method.

5. Using toArray() method
Stream supports to convert Stream to array via toArray() method:

Demonstrate 5 ways to convert stream to list in Java
We are creating main method like this

Convert Stream to List in Java

That’s all about Convert Stream to List in Java.

Java 8 Collectors JavaDoc

Download complete source, click link below (210 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons