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 :)
How to return a Set View of Keys with existing Values?
758 Views Asked by Yusuf At
2
There are 2 best solutions below
2

Streams
- Iterate over entrySet
- Ignore null values
- 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());
}
}
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.
The resulting Set "entrySet" is what you're looking for