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

There are several ways to filter a map in Java, depending on the criteria and the desired output. Here are some of the common methods:

1. Using a loop

We can filter a map by its keys or values using enhanced for loop. This method involves iterating over the map’s entry set and checking each key or value against a condition. The filtered entries can be stored in another map or collection. For example, to filter a map by its keys, we can use the following code:

Download  Run Code

2. Using Stream API

In Java 8 and above, the recommended approach to filter a map by its keys or values is using the Stream API. This method involves converting the map’s entry set into a stream and applying the filter() method with a predicate. Then collect the filtered stream into another map by using the Collectors.toMap() method by providing proper mapping methods for extracting keys and values from stream elements. This can be illustrated by this example:

Download  Run Code

 
The filtered stream can also be collected into a string using the Collectors.joining() method. For example, the following code filters a map by its keys and get the string representation of the filtered map:

Download  Run Code

That’s all about filtering a Map in Java.