Convert a Stream to a List in Java
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.
|
1 2 3 |
Stream<String> stream = Stream.of("C", "C++", "Java"); List<String> list = stream.collect(Collectors.toList()); System.out.println(list.toString()); |
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.
|
1 2 3 |
Stream<String> stream = Stream.of("C", "C++", "Java"); List<String> list = stream.collect(Collectors.toCollection(ArrayList::new)); System.out.println(list.toString()); |
2. Using Divide & Conquer
We can easily divide the problem into two parts:
The following program demonstrates it:
|
1 2 3 4 |
Stream<String> stream = Stream.of("C", "C++", "Java"); String[] lang = stream.toArray(String[]::new); List<String> list = Arrays.asList(lang); System.out.println(list.toString()); |
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.
|
1 2 3 4 |
Stream<String> stream = Stream.of("C", "C++", "Java"); List<String> list = new ArrayList<>(); stream.forEach(list::add); System.out.println(list.toString()); |
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:
|
1 2 3 4 |
Stream<String> stream = Stream.of("C", "C++", "Java"); List<String> list = new ArrayList<>(); stream.parallel().forEachOrdered(list::add); System.out.println(list.toString()); |
That’s all about converting Stream to a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)