0

例如,如果我有一个包含 10 个键的 HashMap,但只有 4 个键有值。如何返回这些键的 SetView。我只找到了 Map<K,V>.keySet() 方法,但是这个方法给了我这个 Hashmap 中的每一个键。我只需要那些价值 !=null !!! 对不起我的英语不好,我是德国人:)

4

2 回答 2

2

  1. 遍历 entrySet
  2. 忽略空值
  3. 收集钥匙
        Map<String, String> map = new HashMap<>();
        map.entrySet().stream()
            .filter(e -> e.getValue() != null)
            .map(Entry::getKey)
            .collect(Collectors.toSet());

使用 for 循环

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

于 2021-02-14T02:39:02.050 回答
-1

使用 keySet() 方法,遍历 Set 中的每个 Entry,每次检查 Entry 的值。如果此“值”为空,则我们将其从 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);
       }
}

结果集“entrySet”就是你要找的

于 2021-02-14T02:35:19.930 回答