簡體   English   中英

如何返回具有現有值的鍵的集合視圖?

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

例如,如果我有一個帶有 10 個鍵的 HashMap,但只有 4 個鍵有值。 如何返回這些鍵的 SetView。 我只找到了 Map<K,V>.keySet() 方法,但是這個方法給了我這個 Hashmap 中的每個鍵。 我只需要那些有值的,= null:!! 對不起我的英語不好,我是德國人:)

  1. 遍歷 entrySet
  2. 忽略 null 值
  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());
            }
        }

使用 keySet() 方法,遍歷 Set 中的每個 Entry,每次檢查 Entry 的值。 如果這個“值”是 null,那么我們將它從 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”就是你要找的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM