gpt4 book ai didi

java - 在 Java 中合并 2 个 HashMap

转载 作者:行者123 更新时间:2023-12-01 19:04:24 25 4
gpt4 key购买 nike

我有一个程序需要合并两个HashMap。 HashMap 有一个 String 键和一个 Integer 值。合并的特殊条件是,如果键已经在字典中,则需要将Integer添加到现有值中,而不是替换它。这是我到目前为止抛出 NullPointerException 的代码。

public void addDictionary(HashMap<String, Integer> incomingDictionary) {
for (String key : incomingDictionary.keySet()) {
if (totalDictionary.containsKey(key)) {
Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key);
totalDictionary.put(key, newValue);
} else {
totalDictionary.put(key, incomingDictionary.get(key));
}
}
}

最佳答案

如果你的代码不能保证incomingDictionary在到达这个方法之前被初始化,你将不得不进行空检查,没有出路

public void addDictionary(HashMap<String, Integer> incomingDictionary) {
if (incomingDictionary == null) {
return; // or throw runtime exception
}
if (totalDictionary == null) {
return;// or throw runtime exception
}
if (totalDictionary.isEmpty()) {
totalDictionary.putAll(incomingDictionary);
} else {
for (Entry<String, Integer> incomingIter : incomingDictionary.entrySet()) {
String incomingKey = incomingIter.getKey();
Integer incomingValue = incomingIter.getValue();
Integer totalValue = totalDictionary.get(incomingKey);
// If total dictionary contains null for the incoming key it is
// as good as replacing it with incoming value.
Integer sum = (totalValue == null ?
incomingValue : incomingValue == null ?
totalValue : totalValue + incomingValue
);
totalDictionary.put(incomingKey, sum);
}
}
}

考虑到 HashMap 允许 null 作为代码中另一个容易出现 NPE 的值

Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key);

如果这两个中的任何一个为 null,您将得到 NPE。

关于java - 在 Java 中合并 2 个 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com