How to filter a map with Java stream

In this post, we are going to see How to filter a map with Java stream.

Filtering a Map using the Java Stream API can be achieved by converting the Map into a stream of Map.Entry objects and then apply a filter operation to select the desired entries. Here’s a complete example with an explanation and output.

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class MapFilterExample {
    public static void main(String[] args) {
        // Create a sample map
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Alice");
        map.put(2, "Bob");
        map.put(3, "Charlie");
        map.put(4, "David");
        map.put(5, "Eve");

        // Filter the map based on a condition using Java Stream API
        Map<Integer, String> filteredMap = map.entrySet()
                .stream()
                .filter(entry -> entry.getKey() % 2 == 0) // Keep only even keys
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // Print the filtered map
        System.out.println("Original Map: " + map);
        System.out.println("Filtered Map (Even keys): " + filteredMap);
    }
}

Explanation:

  1. We start by creating a sample Map named map with key-value pairs.
  2. We use the Java Stream API to filter the map based on a condition. In this example, we are filtering the map to keep only entries with even keys.
  3. We call entrySet() on the map to obtain a stream of Map.Entry objects, which represent key-value pairs.
  4. We use the filter method to specify the condition for filtering. In this case, we use a lambda expression to check if the key of each entry is even (entry.getKey() % 2 == 0).
  5. We use the collect method to collect the filtered entries into a new Map. We use Collectors.toMap to create a new Map with the same key-value type as the original.
  6. Finally, we print both the original and filtered maps to see the result.

Output:

Original Map: {1=Alice, 2=Bob, 3=Charlie, 4=David, 5=Eve}
Filtered Map (Even keys): {2=Bob, 4=David}

As we can see, the Java Stream API allowed us to filter the original Map and create a new Map containing only the entries that met the specified condition (in this case, entries with even keys).

That’s all about How to filter a map with Java stream.

Other Java 8 tutorials.