Map map = new HashMap<Long, Boolean>();
map.keySet(); // filtering the true value
You can filter
over the entrySet
and then use map
to only obtain the keys with streams.
Set<Long> resultKeys = map.entrySet().stream().filter(Map.Entry::getValue)
.map(Map.Entry::getKey).collect(Collectors.toSet());
Try it like this. You're filtering the Map.Entry
on the value and then mapping the entry
to the key
.
Map<Long, Boolean> map =
Map.of(1L, true, 2L, false, 3L, true, 4L, false);
Set<Long> set = map.entrySet().stream()
.filter(Entry::getValue).map(Entry::getKey)
.collect(Collectors.toSet());
System.out.println(set);
Prints
[1, 3]
You can iterate over the map's entry set, and add the key
to a set if the value
is true
:
public static void main(String[] args) {
Map<Long, Boolean> map = new HashMap<Long, Boolean>();
map.put(1l,true); map.put(2l,false); map.put(3l,true);
Set<Long> validKeys = getValidKeys(map);
System.out.println(validKeys);
}
private static Set<Long> getValidKeys(Map<Long, Boolean> map) {
Set<Long> set = new HashSet<>();
for(Map.Entry<Long, Boolean> entry : map.entrySet()) {
if(entry.getValue()) set.add(entry.getKey());
}
return set;
}
Output:
[1, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.