用Java合并2个HashMap

我有一个程序需要合并两个HashMap。哈希图的键为a

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会在到达此方法之前将其初始化,则您将必须执行null检查,没有出路

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);

如果这两个都不为空,则将获得NPE。

以上是 用Java合并2个HashMap 的全部内容, 来源链接: utcz.com/qa/417353.html

回到顶部