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}

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of