Map map = new HashMap<Long, Boolean>();
map.keySet(); // filtering the true value发布于 2021-02-24 06:00:05
像这样试一下。您将根据值过滤Map.Entry,然后将entry映射到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);打印
[1, 3]发布于 2021-02-24 06:03:46
如果value为true,则可以遍历地图的条目集合,并将key添加到集合
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;
}输出:
[1, 3]https://stackoverflow.com/questions/66341633
复制相似问题