Java 8 Convert a Stream to List Example
Hello readers, this tutorial explains how to convert a Stream to a List with the help of the following examples.
One of the common problem while working with the Stream API in Java 8 is how to convert a Stream to List in Java because there is no
toList() method present in the Stream class. When developers are processing a List using the Stream’s map and filter method, they ideally want the result in some collection so that they can pass it to the other part of the program. Though
java.util.stream.Stream class has a
toArray() method to convert the Stream to Array, there is no similar method to convert the Stream to List or Set. Java has a design philosophy of providing conversion methods between the new and old API classes. For e.g. When they introduced the Path class in JDK 1.7, which is similar to the
java.io.File, they provided a
toPath() method to the File class.
Similarly JDK developers could have provided convenient methods like
toSet()into the Stream class, but unfortunately, they have not done that. Anyway, it seems JDK developers did think about this and provided a class called Collector to collect the result of the stream operations into the different container or the Collection classes. Here developers will find methods like
toList(), which can be used to convert the Java 8 Stream to List. They can also use any List implementation class such as
LinkedListto get the contents of that Stream.
I would have preferred having those method at-least the common ones directly into Stream but nevertheless, there is something we can use to convert a Java 8 Stream to List. Here is
5 simple ways to convert a Stream to List. For e.g. converting a Stream of String to a List of String or converting a Stream of Integer to a List of Integer and so on.
1.1 Using Collectors.toList() method
This is the standard way to collect the result of a stream in a container i.e. List, Set or any other Collection. Stream class has a
collect() method which accepts a Collector and developers can use the
Collectors.toList() method to collect the result in a List. Let’s see the simple code snippet that follows this implementation.
List listOfStream = streamOfString.collect(Collectors.toList());
1.2 Using Collectors.toCollection() method
This is actually a generalization of the previous method i.e. here instead of creating a List, developers can collect the elements of Stream in any Collection (such as
LinkedList or any other List). In this example, we are collecting the Stream elements into
toCollection() method returns a Collector that accumulates the input elements into a new Collection. The Collection is created by the provided supplier instance, in this case, we are using
ArrayList :: new i.e. a constructor reference to collect them into the
ArrayList. Developers can also use a Lambda Expression in place of Method Reference, but the method reference results in much more readable and concise code. Let’s see the simple code snippet that follows this implementation.
List listOfString = streamOfString.collect(Collectors.toCollection(ArrayList :: new));
1.3 Using forEach() method
Developers can also use the
forEach() method to go through all the elements of a Stream one by one and add them to a new
List or the
ArrayList. This is the simple and pragmatic approach which beginners can use to learn. Let’s see the simple code snippet that follows this implementation.
Stream streamOfLetters = Stream.of("Abc", "Cde", "Efg", "Jkd", "Res"); ArrayList list = new ArrayList<>(); streamOfLetters.forEach(list :: add);
1.4 Using forEachOrdered() method
If Stream is parallel then the elements may be processed out of order but if developers want to add them into the same order as they were present in the Stream, they can use the
forEachOrdered() method. Let’s see the simple code snippet that follows this implementation.
1.5 Using toArray() method
The Stream provides a direct method to convert the Stream to Array (i.e.
toArray() method). The method which accepts the no argument returns an object array as shown in this sample program, but developers can still get which type of array they want by using the overloaded version of the method. Let’s see the simple code snippet that follows this implementation.
Stream streamOfShapes = Stream.of("Rectangle", "Square", "Circle", "Oval"); String arrayOfShapes = streamOfShapes.toArray(String::new); List listOfShapes = Arrays.asList(arrayOfShapes);
Now, open up the Eclipse Ide and let’s see a few examples of Matching in Java!
2. Java 8 Convert a Stream to List Example
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to
File -> New -> Maven Project.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a
pom.xml file will be created. It will have the following code:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaStreams2List</groupId> <artifactId>JavaStreams2List</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
Developers can start adding the dependencies that they want. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Java Class Creation
Let’s create the required Java files. Right-click on the
New -> Package.
A new pop window will open where we will enter the package name as
Once the package is created in the application, we will need to create the model and the implementation classes to illustrate the Java 8 Streams examples. Right-click on the newly created package:
New -> Class.
A new pop window will open and enter the file name as:
Java8StreamToList. The implementation class will be created inside the package:
3.1.1 Implementation of Model Class
Here is the complete Java program to demonstrate the above
5 methods of converting the Java8 Streams to List. Let’s see the simple code snippet that follows this implementation.
Do remember, developers will have to use the ‘JDK 1.8‘ dependency for implementing the Stream’s usage in their applications.
4. Run the Application
To run the application, right-click on the
-> Run As -> Java Application. Developers can debug the example and see what happens after every step!
5. Project Demo
The application shows the following logs as output for the
That’s all for this post. Happy Learning!!
That’s all about how to convert the Stream to List in Java8. Developers have seen that there are several ways to perform the conversion but I would suggest sticking with the standard approach i.e. by using the
Stream.collect(Collectors.toList()) method. I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Stream to List conversion in Java8.
You can download the full source code of this example here: JavaStreams2List