How to convert a Stream to a List in Java 8

In Java 8, a Stream class can be converted to a List using the collect method of the Collectors class.

Syntax:

List<String> list = stream.collect( Collectors.toList() );

Example:

Here is an example converting a Stream to a List. First the code creates a Stream of String, then the collect method is called to return a List. Finally, all the elements for the List are written in the output.

Create the following java file:

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

public class LambdaStreamList {

	public static void main(String[] argv){
		// Create the Stream
		Stream<String> stream = Stream.of( "a", "c", "a", "b", "b");
		
		// Convert the Stream to a List
		List<String> list = stream.collect( Collectors.toList() );
		
		// Display the ouput
		System.out.println( "List: " + list );
		
	}
}

The output will be:

List: [a, c, a, b, b]

References:

Lambda Expressions

Recent Comments