How to Filter a Map in Java

In Java, maps provide a convenient way to store key-value pairs. Filtering a map involves selectively extracting elements based on specific conditions. Whether you want to remove certain entries or create a new map with filtered data, this article will guide you through various techniques for filtering maps in Java.

Filtering with Traditional Loop

The simplest approach to filter a map is by using a traditional loop. Iterate over the map’s entry set and evaluate each entry against your desired condition. If the condition is met, add the entry to a new map.

package io.devqa.java.examples;

import java.util.HashMap;
import java.util.Map;

public class FilterMapExamples {

    public static void main(String[] args) {
        Map<Integer, String> originalMap = new HashMap<>();
        originalMap.put(1, "Apple");
        originalMap.put(2, "Banana");
        originalMap.put(3, "Orange");
        originalMap.put(4, "Grapes");

        Map<Integer, String> filteredMap = new HashMap<>();

        for (Map.Entry<Integer, String> entry : originalMap.entrySet()) {
            if (entry.getKey() > 2) {
                filteredMap.put(entry.getKey(), entry.getValue());
            }
        }

        System.out.println("Filtered Map: " + filteredMap);
    }
}

Output

Filtered Map: {3=Orange, 4=Grapes}

Filtering with Java 8 Stream API

Java 8 introduced the Stream API, which offers powerful functional programming features. Using streams and lambda expressions, you can succinctly filter maps.

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

public class MapFilteringExample {
    public static void main(String[] args) {
        Map<Integer, String> originalMap = new HashMap<>();
        originalMap.put(1, "Apple");
        originalMap.put(2, "Banana");
        originalMap.put(3, "Orange");
        originalMap.put(4, "Grapes");

        Map<Integer, String> filteredMap = originalMap.entrySet()
                .stream()
                .filter(entry -> entry.getKey() > 2)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println("Filtered Map: " + filteredMap);
    }
}

Output

Filtered Map: {3=Orange, 4=Grapes}

Filtering with Java 8 Stream API and Predicate

If you need to apply multiple filtering conditions, it’s beneficial to use a Predicate. A Predicate is a functional interface that accepts an argument and returns a boolean. It allows you to define reusable conditions.

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

public class MapFilteringExample {
    public static void main(String[] args) {
        Map<String, Integer> originalMap = new HashMap<>();
        originalMap.put("Apple", 10);
        originalMap.put("Banana", 20);
        originalMap.put("Orange", 15);
        originalMap.put("Grapes", 5);

        Predicate<Map.Entry<String, Integer>> filterCondition = entry -> entry.getValue() >= 10;

        Map<String, Integer> filteredMap = originalMap.entrySet()
                .stream()
                .filter(filterCondition)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println("Filtered Map: " + filteredMap);
    }
}

Output

Filtered Map: {Apple=10, Orange=15, Banana=20}

Conclusion

Filtering maps in Java allows you to extract specific data based on defined conditions. Whether you prefer using traditional loops or leverage the powerful Stream API, Java provides multiple options to filter maps efficiently. With the example code and outputs provided, you can easily understand and apply these techniques to manipulate and extract data from maps in Java.