How to Filter a Map in Java

1. Introduction

Filtering a Map in Java involves selecting entries based on specific criteria. This can be particularly useful when you need to process or analyze data stored in map structures. Java provides multiple ways to perform filtering, including using loops, the Stream API introduced in Java 8, and external libraries like Google Guava. This blog post will demonstrate different methods to filter a Map in Java.

2. Program Steps

1. Create a Map and populate it with some key-value pairs.

2. Filter the Map using a loop and conditional statements.

3. Filter the Map using the Java 8 Stream API.

4. (Optional) Filter the Map using Google Guava if external libraries are used.

3. Code Program

import java.util.*;
import java.util.stream.Collectors;

public class FilterMap {
    public static void main(String[] args) {
        // Creating and populating a Map
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");
        map.put(4, "Four");
        map.put(5, "Five");

        // Method 1: Filtering using a loop
        Map<Integer, String> filteredMapUsingLoop = new HashMap<>();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            if (entry.getKey() % 2 == 0) { // Condition to filter even keys
                filteredMapUsingLoop.put(entry.getKey(), entry.getValue());
            }
        }

        // Method 2: Filtering using the Stream API
        Map<Integer, String> filteredMapUsingStream = map.entrySet().stream()
            .filter(entry -> entry.getKey() % 2 == 0) // Filtering condition
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // Displaying the original Map
        System.out.println("Original Map: " + map);

        // Displaying the filtered Maps
        System.out.println("Filtered Map using loop: " + filteredMapUsingLoop);
        System.out.println("Filtered Map using Stream API: " + filteredMapUsingStream);
    }
}

Output:

Original Map: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Filtered Map using loop: {2=Two, 4=Four}
Filtered Map using Stream API: {2=Two, 4=Four}

Explanation:

1. The program starts by creating a HashMap named map and populating it with integer keys and string values.

2. The first method for filtering uses a for-loop to iterate over the map's entry set. It checks each entry's key to determine if it is even (entry.getKey() % 2 == 0). If the condition is met, the entry is added to a new HashMap named filteredMapUsingLoop.

3. The second method utilizes the Stream API. The map.entrySet().stream() creates a stream of map entries, which is then filtered using .filter(entry -> entry.getKey() % 2 == 0). The filtered stream is collected into a new HashMap using Collectors.toMap(), resulting in filteredMapUsingStream.

4. Both filteredMapUsingLoop and filteredMapUsingStream contain only the entries from the original map that have even keys, as demonstrated by the filtering condition.

5. This example illustrates two approaches to filtering a Map in Java, showcasing both an imperative approach using loops and a declarative approach using the Stream API.

Comments