How to get all keys whose values are null in Java 8 using Map

I was going through How to remove a key from HashMap while iterating over it?, but my requirement is bit different.

class Main {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();

        hashMap.put("RED", "#FF0000");
        hashMap.put("BLACK", null);
        hashMap.put("BLUE", "#0000FF");
        hashMap.put("GREEN", "#008000");
        hashMap.put("WHITE", null);

        // I wan't result like below - get All keys whose value is null
        List<String> collect = hashMap.values()
                .stream()
                .filter(e -> e == null)
                .collect(Collectors.toList());
        System.out.println(collect);
        
        // Result - BLACK, WHITE in list
    }
}

>Solution :

Try this:

import java.util.*;
import java.util.stream.*;
class Main {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();

        hashMap.put("RED", "#FF0000");
        hashMap.put("BLACK", null);
        hashMap.put("BLUE", "#0000FF");
        hashMap.put("GREEN", "#008000");
        hashMap.put("WHITE", null);

        // I wan't result like below - get All keys whose value is null
        List<String> collect = hashMap.keySet()
                .stream()
                .filter(e -> Objects.isNull(hashMap.get(e)))
                .collect(Collectors.toList());
        System.out.println(collect);
        
        // Result - BLACK, WHITE in list
    }
}

As pointed out in the comments, you can try this as well:

import java.util.*;
import java.util.stream.*;
class Main {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();

        hashMap.put("RED", "#FF0000");
        hashMap.put("BLACK", null);
        hashMap.put("BLUE", "#0000FF");
        hashMap.put("GREEN", "#008000");
        hashMap.put("WHITE", null);

        // I wan't result like below - get All keys whose value is null
        List<String> collect = hashMap.entrySet()
                .stream()
                .filter(e -> Objects.isNull(e.getValue()))
                .map(e -> e.getKey())
                .collect(Collectors.toList());
        System.out.println(collect);
        
        // Result - BLACK, WHITE in list
    }
}

This is more optimized, as compared to the first solution.

Leave a Reply