In this post, we’ll illustrate how to filter a list in Java.

1. Java 7 and before

A naive approach is to iterate through the list using the for-each loop and filter it using a conditional statement.

Download  Run Code

Output:

[BLUE, BLACK, BROWN]

 
The above solution creates a separate list for filtered elements. We can also filter the same list using an iterator.

The following code uses the remove() method provided by the Iterator class to filter the list elements. Please note that ConcurrentModificationException will be thrown if the remove() method of List interface is used, as it is not allowed to modify a list while iterating over it except by iterator’s own remove method.

Download  Run Code

Output:

[BLUE, BLACK, BROWN]

2. Using Java 8 Stream

In Java 8 and above, the recommended approach is to convert the list into a stream, apply a filter on it, and finally, collect the filtered elements in a String.

Download  Run Code

Output:

[BLUE, BLACK, BROWN]

 
We can also convert the filtered stream back to a list by using a list collector.

Download  Run Code

Output:

[BLUE, BLACK, BROWN]

That’s all about filtering List in Java.