Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HashMap如何获取未链接到HashMap的密钥集?_Java_Hashmap - Fatal编程技术网

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

Java HashMap如何获取未链接到HashMap的密钥集?,java,hashmap,Java,Hashmap,我有一个HashMap,它存储需要更改的数据。我需要计算HashMap中有多少字段,不包括“注释”和“调试”。我的解决方案是简单地获取键集,并删除我不想计数的列,如下所示: // Create and populate the HashMap HashMap<String, String> updates = new HashMap<>(); makeUpdates(updates); if (somecondition) { updates.put("comme

我有一个HashMap,它存储需要更改的数据。我需要计算HashMap中有多少字段,不包括“注释”和“调试”。我的解决方案是简单地获取键集,并删除我不想计数的列,如下所示:

// 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());
//创建并填充HashMap
HashMap updates=新建HashMap();
makeUpdates(更新);
如果(某些条件){
updates.put(“评论”,commentUpdater(“一些评论”);
}
updates.put(“debug”,getDebugInfo());
//获取更新的密钥
设置updatedFields=更新
更新字段。删除(“注释”);
删除(“调试”);
System.out.println(“以下”+updatedFields.size()+
字段已更新:“+updatedFields.toString());

当然,问题是从集合中删除“注释”和“调试”也会从HashMap中删除它们。如何断开此链接,或获取未链接到HashMap的集合的副本?

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

Set updatedFields=newhashset(updates.keySet());
创建副本

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

为什么不从总数中减去两个,然后在输出时过滤掉呢?代码中没有显示(编辑以修复),这是一种边缘情况,有时注释字段实际上没有设置。我不相信“注释”和“调试”应该在映射中。如果要对这些键进行不同的处理,最好将它们分开。
Set<String> updatedFields = new HashSet<>(updates.keySet());
Set<String> updatedFields = updates.keySet()
                                   .stream()
                                   .filter(key -> !"comments".equals(key) && !"debug".equals(key))
                                   .collect(Collectors.toSet());