This post will discuss how to convert a list to stream in Java 8 and above. We will also discuss how to apply filters on a stream and convert it back to a list.

1. Convert a list to Stream

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

Download  Run Code

Output:

[New York, Tokyo, New Delhi]

2. Filter stream using a Predicate

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

In the following example, we’ll create a stream of string objects using Collection.stream() and filter it to produce a stream containing strings starting with “N”.

Download  Run Code

Output:

New York
New Delhi

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

3. Convert stream back to list

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

Download  Run Code

Output:

[1, 2, 3, 4, 5]

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

That’s all about converting a List to Stream in Java.