In this tutorial, we are going to filter a Map in Java 8. We have been filtering the map in Java since over the years. But in previous versions of Java, if we want to filter a Map, we should loop the map and put a condition inside the loop based on the requirement.

Legacy Style to Filter a Map :

Map<Integer,String> mobiles = new HashMap<>();
        mobiles.put(1, "iPhone 7");
        mobiles.put(2, "iPhone 6S");
        mobiles.put(3, "Samsung");
        mobiles.put(4, "1+");
        for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {
            if(mobis.getValue().equals("Samsung")){
                System.out.println("Filtered Value : "+mobis.getValue());
            }
        }

On the above, we have filtered a samsung mobile among 4.

Now we will see how do we do filter a Map in Java 8 using Stream API.

Filter a Map in Java 8 :

We can filter a Map in Java 8 by converting the map.entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.

String result = mobiles.entrySet().stream() // converting into Stream
               .filter(map -> "Samsung".equals(map.getValue())) // Applying filter
               .map(map -> map.getValue()) // apply mapping
               .collect(Collectors.joining()); // collecting the data

Complete Example:

Java8_FilterMap
package com.onlinetutorialspoint.java8;

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

public class Java8_FilterMap {
    public static void main(String[] args) {
        Map<Integer,String> mobiles = new HashMap<>();
        mobiles.put(1, "iPhone 7");
        mobiles.put(2, "iPhone 6S");
        mobiles.put(3, "Samsung");
        mobiles.put(4, "1+");
        for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {
            if(mobis.getValue().equals("Samsung")){
                System.out.println("Filtered Value : "+mobis.getValue());
            }
        }
        // Java8 Filtering
        
        String result = mobiles.entrySet().stream()
                .filter(map -> "Samsung".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("Filtering With Value " + result);
        
        
        Map<Integer, String> deptMap2 = mobiles.entrySet().stream()
                .filter(map -> map.getKey() == 2)
                .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        
        System.out.println("Filtering With Key : " + deptMap2);
    }
}

Output:

Terminal
Java8_FilterMap
Filtered With Value Samsung
Filtered With Key : {2=iPhone 6S}

Happy Learning 🙂