Filter List in Java

In this post, we will illustrate how to filter list in Java.


 

1. Java 7 and before

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

Download   Run Code

Output:

[BLUE, BLACK, BROWN]

Above solution creates a seperate list for filtered elements. We can also filter the same list using an iterator.

Below code uses remove() method provided by Iterator class to filter the elements from the list. Please note that ConcurrentModificationException will be thown if 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. Java 8 Stream

In Java 8 and above, the recommended approach is to convert the list into a Stream, apply 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]

 
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