Core Java

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.

1. Introduction

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 toList(), 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 ArrayList or LinkedList to 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 ArrayList, LinkedList or any other List). In this example, we are collecting the Stream elements into ArrayList. The 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.

Stream streamOfNumbers = Stream.of("Java", "C++", "JavaScript", "Scala", "Python");
ArrayList myList = new ArrayList<>();
streamOfNumbers.parallel().forEachOrdered(myList :: add);

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!

Fig. 1: Stream to List Conversion Example
Fig. 1: Application Project Structure

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.

Fig. 2: Create Maven Project
Fig. 2: Create 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.

Fig. 3: Project Details
Fig. 3: Project Details

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: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

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:

pom.xml

<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 src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

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.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: Java8StreamToList. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (Java8StreamToList.java)
Fig. 8: Java Class (Java8StreamToList.java)

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.

Java8StreamToList.java

package com.jcg.java;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8StreamToList {

	private static void streamToList() {

		ArrayList<String> myList = null;
		List<String> listOfStream = null;
		Stream<String> streamOfString = null;

		/***** Converting Stream to List Using The 'Collectors.toList()' Method *****/ 
		streamOfString = Stream.of("Code", "Logic", "Program", "Review", "Skill");
		listOfStream = streamOfString.collect(Collectors.toList());
		System.out.println("Example #1 - Java8 Stream to List?= " + listOfStream);

		/***** Java8 Stream to ArrayList Using 'Collectors.toCollection' Method *****/
		streamOfString = Stream.of("One", "Two", "Three", "Four", "Five");
		listOfStream = streamOfString.collect(Collectors.toCollection(ArrayList :: new));
		System.out.println("Example #2 - Java8 Stream to List?= " + listOfStream);

		/***** IIIrd Way To Convert Stream To List In Java8 *****/
		streamOfString = Stream.of("Abc", "Cde", "Efg", "Jkd", "Res");
		myList = new ArrayList<String>();
		streamOfString.forEach(myList :: add);
		System.out.println("Example #3 - Java8 Stream to List?= " + myList);

		/***** IVth Way To Convert Parallel Stream to List *****/
		streamOfString = Stream.of("Java", "C++", "JavaScript", "Scala", "Python");
		myList = new ArrayList<String>();
		streamOfString.parallel().forEachOrdered(myList :: add);
		System.out.println("Example #4 - Java8 Stream to List?= " + myList);

		/***** Vth Way Of Creating List From Stream In Java. But Unfortunately This Creates Array Of Objects As Opposed To The Array Of String *****/
		streamOfString = Stream.of("James", "Jarry", "Jasmine", "Janeth");
		Object[] arrayOfString = streamOfString.toArray();
		List<Object> listOfNames = Arrays.asList(arrayOfString);
		System.out.println("Example #5 - Java8 Stream to List?= " + listOfNames);

		/***** Can We Convert The Above Method To String[] Instead Of Object[], 'Yes' By Using Overloaded Version Of 'toArray()' As Shown Below *****/ 
		streamOfString = Stream.of("Rectangle", "Square", "Circle", "Oval");
		String[] arrayOfShapes = streamOfString.toArray(String[] :: new);
		listOfStream = Arrays.asList(arrayOfShapes);
		System.out.println("Modified Version Of Example #5?= " + listOfStream);
	}

	public static void main(String[] args) {
		streamToList();
	}
}

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 Java8StreamToList class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The application shows the following logs as output for the Java8StreamToList.java.

Example #1 - Java8 Stream to List?= [Code, Logic, Program, Review, Skill]
Example #2 - Java8 Stream to List?= [One, Two, Three, Four, Five]
Example #3 - Java8 Stream to List?= [Abc, Cde, Efg, Jkd, Res]
Example #4 - Java8 Stream to List?= [Java, C++, JavaScript, Scala, Python]
Example #5 - Java8 Stream to List?= [James, Jarry, Jasmine, Janeth]
Modified Version Of Example #5?= [Rectangle, Square, Circle, Oval]

That’s all for this post. Happy Learning!!

6. Conclusion

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.

Download
You can download the full source code of this example here: JavaStreams2List

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button