0

I want to check keys of origMap with otherMap .if it found take the value from othermap as key and value of origMap as value

place it into new hashmap. if not found calculate the all values of origmap using Bigdecimal place in the same map as key "other" and value as bigdecimal output. I am trying like below but it's not working throwing null pointer,not sure what is the issue.

Maps:

HashMap < String, Object > origMap = new HashMap < String, Object > ();
origMap.put("test", "1");
origMap.put("test2", "100.00");
origMap.put("test3", "3");
origMap.put("test4", "300.23");

HashMap < String, Object > otherMap = new HashMap < String, Object > ();
otherMap.put("test3", "fee");
otherMap.put("test2", "tax");

code:

Map newMap = new HashMap();
BigDecimal value1 = null;
for (Map.Entry <? , ?> me: origMap.entrySet())
{
    String key = "";
    String value = "";
    if (otherMap.get(key).equals(me.getKey()))
    {
        key = otherMap.get(me.getKey()).toString();
        value = origMap.get(me.getKey()).toString();
        newMap.put(key, value);
    }
    else
    {
        value = origMap.get(me.getKey()).toString();
        value1 = value1.add(new BigDecimal(value));
    }

    queryMap.put("others", value1);
}
4

1 回答 1

1

otherMap.get(key)将找不到条目key="",​​因此调用equals(...)将引发 NPE。

由于您似乎在尝试检查是否有me.getKey()in otherMaptryotherMap.get(me.getKey()) != nullotherMap.containsKey(me.getKey()=)instead 的条目。

此外,otherMap.get(key).equals(me.getKey())在您的情况下永远不会成立(与 的值无关key),因为您将值 fromotherMap与键 from进行比较origMap

另请注意,调用toString()也可能导致 NPE,除非您确定没有空值。

我将尝试将您的代码重组为我认为您想要的:

Map<String, String> newMap=new HashMap<>(); //as of Java 7
BigDecimal value1=null;
for (Map.Entry<String,Object> me : origMap.entrySet()) {  
  if(otherMap.containsKey( me.getKey() )) {
    Object otherValue = otherMap.get(me.getKey());
    Object origValue =  origMap.get(me.getKey());
    String key = otherValue != null ? otherValue.toString() : null; //note: this might cause problems if null keys are not allowed
    String value = origValue != null ? origValue.toString() : null;
    newMap.put(key, value);
  }else {
    Object origValue =  origMap.get(me.getKey());
    if( origValue != null ) {
      value1=value1.add(new BigDecimal( origValue.toString())); //note: this might cause NumberFormatException etc. if the value does not represent a parseable number
    }
  }

  queryMap.put("others", value1);
}

顺便说一句,如果所有值都是字符串,为什么是origMapotherMap类型?Map<String, Object>在那种情况下Map<String, String>会更合适,因此不需要toString()调用(以及空检查)。

于 2013-08-22T11:09:18.503 回答