Convert a List to Stream in Java 8

In this post, we will see how to convert a list to stream in Java 8. We will also discuss how to apply filters on a stream and convert stream back to a list.

 

1. Convert a List to Stream

Converting a list to stream is very simple. As List extends Collection interface, we can use Collection.stream() method that returns a sequential stream of elements in the list.

Java

Download   Run Code

Output:

[New York, Tokyo, New Delhi]

 

2. Filter Stream using a Predicate

For filtering a stream, we can use filter(Predicate) method that returns a stream consisting of elements matching the specified predicate.

In below example, we will create a stream of String objects using Collection.stream() and filter it to produce a stream containing strings starting with “N”.

Java

Download   Run Code

Output:

New York
New Delhi

We can also specify a lambda expression or method reference in place of predicate –

 

3. Convert Stream back to List

We can accumulate the elements of the stream into a new List using a Collector returned by Collectors.toList().

Java

Download   Run Code

Output:

[1, 2, 3, 4, 5]

We can also accumulate elements of the stream into a set using Collectors.toSet() as shown below:

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz