Java Stream to List

Convert Stream to List in java

In this post, we will see how to convert Stream to List in java.

There are multiple ways to convert Stream to List in java.

Using Collectors.toList()

You can pass Collectors.toList() to Stream.collect() method to convert Stream to List in java. Stream’s collect method performs mutable reduction operation on elements of Stream and Collectors.toList() provides a collector which accumulates elements of Stream into the list.

Here is an quick example:

Output:

[India, China, France, Germany]

Using Collectors.toCollection()

You can pass Collectors.toCollection() to Stream.collect() method to convert Stream to List in java. This is similar to previous approach, but it gives you more control over type of collection you want.

Here is an example to create LinkedList from Stream.

[India, China, France, Germany]

Using foreach

You can iterate over Stream using foreach() method and add elements to the List.

Here is an example to create LinkedList from Stream.

This approach is not recommended in case you are using Parallel Stream as elements of the Streams may not be processed in original order. You can use forEachOrdered() method to preserve the order in the List.
Output:

[India, China, France, Germany]

Filter Stream and convert to List

If you want to filter elements from Stream, you can use Stream’s filter method.

Output:

[India, Indonesia]

Filter method accepts predicate functional interface to filter a Stream.

Convert infinite Stream to List

You need to limit infinite Stream and then convert it to list.

Here is an exmple:

Output:

[100, 101, 102, 103, 104]

Here we have used iterate() method to generate an infinite Stream and limited it using limit() method and then converted it to list.

That’s all about Java Stream to List.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *