![](/img/trans.png)
[英]Iterate through TreeMap - Return a set of all values of the keys of the map
[英]How to return a Set View of Keys with existing Values?
例如,如果我有一個帶有 10 個鍵的 HashMap,但只有 4 個鍵有值。 如何返回這些鍵的 SetView。 我只找到了 Map<K,V>.keySet() 方法,但是這個方法給了我這個 Hashmap 中的每個鍵。 我只需要那些有值的,= null:!! 對不起我的英語不好,我是德國人:)
Map<String, String> map = new HashMap<>();
map.entrySet().stream()
.filter(e -> e.getValue() != null)
.map(Entry::getKey)
.collect(Collectors.toSet());
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.