Filter Map in Java

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


 

1. Naive approach (Java 7 and before)

The naive approach is to iterate through the map using entrySet() and filter it based on key or value using a conditional statement.

Download   Run Code

Output:

{BLUE=#0000FF, BLACK=#000000, BROWN=#A52A2A}

 

2. Java 8 Stream

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

Download   Run Code

Output:

{BLUE=#0000FF, BLACK=#000000, BROWN=#A52A2A}

 
We can also convert the filtered Stream back to a Map by providing proper mapping functions for extracting keys and values from elements of the stream.

Download   Run Code

Output:

{BLUE=#0000FF, BLACK=#000000, BROWN=#A52A2A}

 
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