用Java合并2个HashMap [英] Merging 2 HashMaps in Java

查看:893
本文介绍了用Java合并2个HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program that needs to merge two HashMap. The hashmaps have a key that is a String and a value that is an Integer. The special condition of the merge is that if the key is already in the dictionary, the Integer needs to be added to the existing value and not replace it. Here is the code I have so far that is throwing a 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检查,没有出路

If your code cannot guarantee that incomingDictionary will be initialized before it reaches this method, you will have to do a null check, no way out

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的另一个位置

Considering HashMap allows null as value another place in your code which is prone to NPE is

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

如果这两个都不为空,您将获得NPE.

if either of these two is null you will get NPE.

这篇关于用Java合并2个HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆