简体   繁体   English

Java HashMap如何获取未链接到HashMap的键集?

[英]Java HashMap How to get the set of keys that is not linked to the HashMap?

I have a HashMap that stores data that need to be changed. 我有一个HashMap,用于存储需要更改的数据。 I need to figure out how many fields are in the HashMap, not counting "comments" and "debug". 我需要弄清楚HashMap中有多少个字段,不包括“注释”和“调试”。 My solution was to simply get the keySet, and remove the columns I don't want to count, like this: 我的解决方案是简单地获取keySet,并删除我不想计数的列,如下所示:

// Create and populate the HashMap
HashMap<String, String> updates = new HashMap<>();
makeUpdates(updates);
if (somecondition) {
    updates.put("comments", commentUpdater("Some Comment"));
}
updates.put("debug", getDebugInfo());

// Get the updated keys
Set<String> updatedFields = updates
updatedFields.remove("comments");
updatedFields.remove("debug");
System.out.println("The following " + updatedFields.size() + 
    " fields were updated: " + updatedFields.toString());

The problem, of course, is that removing "comments" and "debug" from the set also removes them from the HashMap. 当然,问题在于从集合中删除“注释”和“调试”也会将它们从HashMap中删除。 How can I break this link, or get a copy of the set that is not linked to the HashMap? 如何断开此链接,或获取未链接到HashMap的集合的副本?

Create a copy 建立副本

Set<String> updatedFields = new HashSet<>(updates.keySet());

Now, you can remove strings from updatedFields which won't affect the updates map. 现在,您可以从updatedFields中删除不会影响updates映射的字符串。

Or as @Elliott Frisch mentioned, you can filter it 或者如@Elliott Frisch所述,您可以对其进行过滤

Set<String> updatedFields = updates.keySet()
                                   .stream()
                                   .filter(key -> !"comments".equals(key) && !"debug".equals(key))
                                   .collect(Collectors.toSet());

创建一个新的HashSet ,并使用HashMapkeySet()的元素对其进行初始化:

Set<String> updatedFields = new HashSet<>(updates.keySet());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM