In Java 8, a Stream class can be converted to a List using the collect method of the Collectors class.
List<String> list = stream.collect( Collectors.toList() );
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.
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 );
}
}
List: [a, c, a, b, b]