How to return a Set View of Keys with existing Values?

758 Views Asked by At

for example if I have a HashMap with 10 keys, but only 4 keys have a value. How can I return a SetView of these keys. I only found the Map<K,V>.keySet()-method but this method is giving me EVERY Key in this Hashmap. I only need the ones with value !=null !!! Sorry for my bad English, im German :)

2

There are 2 best solutions below

4
On

Use the keySet() method, and loop through each Entry in the Set, checking the value of the Entry each time. If this "value" is null, then we remove it from the Set.

Set<Map.Entry<String, String>> entrySet = new HashSet<>(yourMap.entrySet());
for(Map.Entry<String, String> entry : entrySet){
       if(entry.getValue() == null){
            entrySet.remove(entry);
       }
}

The resulting Set "entrySet" is what you're looking for

2
On

Streams

  1. Iterate over entrySet
  2. Ignore null values
  3. Collect the keys
        Map<String, String> map = new HashMap<>();
        map.entrySet().stream()
            .filter(e -> e.getValue() != null)
            .map(Entry::getKey)
            .collect(Collectors.toSet());

Use for loop

        Set<String> keys = new HashSet<>();
        for (Map.Entry<String, String> e : map.entrySet()) {
            if (e.getValue() != null) {
                keys.add(e.getKey());
            }
        }