1. Introduction

Filtering a Map in Java can be accomplished using the Stream API introduced in Java 8. The filter() method of the Stream interface takes a Predicate and retains only those elements that satisfy the given predicate. This tutorial demonstrates how to filter a Map based on a condition applied to its keys or values.

2. Program Steps

1. Create a Map of String keys and Integer values.

2. Print the original Map.

3. Use the entrySet().stream() to convert the Map‘s entry set to a Stream.

4. Use the filter() method to filter the Stream based on a condition applied to the keys or values.

5. Collect the result back into a new Map.

6. Print the filtered Map.

3. Code Program

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

public class FilterMap {

    public static void main(String[] args) {

        // Step 1: Create a Map of String keys and Integer values
        Map<String, Integer> fruits = new HashMap<>();
        fruits.put("Apple", 10);
        fruits.put("Banana", 5);
        fruits.put("Cherry", 15);
        fruits.put("Date", 20);

        // Step 2: Print the original Map
        System.out.println("Original Map: " + fruits);

        // Step 3: Convert the Map&apos;s entry set to a Stream
        // Step 4: Use the filter() method to filter the Stream based on a condition
        // Step 5: Collect the result back into a new Map
        Map<String, Integer> filteredFruits = fruits.entrySet().stream()
                                                    .filter(entry -> entry.getValue() > 10)
                                                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // Step 6: Print the filtered Map
        System.out.println("Filtered Map (Values > 10): " + filteredFruits);
    }
}

Output:

Original Map: {Apple=10, Banana=5, Cherry=15, Date=20}
Filtered Map (Values > 10): {Cherry=15, Date=20}

4. Step By Step Explanation

Step 1: A Map named fruits is created with String keys representing fruit names and Integer values representing their quantities.

Step 2: The original Map, fruits, is printed to the console.

Step 3: The entrySet() of the Map is converted to a Stream using the stream() method.

Step 4: The filter() method is used to retain only those entries whose values are greater than 10. The Predicate here is entry -> entry.getValue() > 10.

Step 5: The filtered Stream is collected back into a new Map named filteredFruits using the collect() method and Collectors.toMap(). The keys and values are extracted using Map.Entry::getKey and Map.Entry::getValue method references.

Step 6: The filtered Map filteredFruits is printed to the console.