2013-08-22 134 views
0

我要检查origMap的按键与otherMap。如果它发现从采取的othermap值作为origMap的键和值值用java低吞吐量

将其放入新的HashMap的HashMap的键比较。如果未找到,则使用Bigdecimal地点与关键字“other”中的Bigdecimal地点计算origmap的所有值,并将值设置为bigdecimal输出。我想下面,但它不工作投掷空指针,不知道是什么问题。

地图:

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

代码:

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); 
} 
+0

堆栈oveflow不允许添加代码,我正在尝试。 – user2684215

+3

再努力尝试;) – Thomas

+0

至于NullPointerException,请标记它出现的位置。 – Thomas

回答

1

otherMap.get(key)不会找到key=""的条目,从而调用equals(...)将抛出NPE。

由于您似乎试图检查是否有me.getKey()的条目在otherMap尝试使用otherMap.get(me.getKey()) != nullotherMap.containsKey(me.getKey()=)

此外,otherMap.get(key).equals(me.getKey())将永远不会在你的情况真(独立上的key值),因为你从otherMaporigMap键比较值。

另请注意,除非您确定没有空值,否则致电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); 
} 

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

+0

是任何在构建方法是否有防止空指针exception.and这里我检查1键到n键。如何优化这个。 – user2684215

+0

我必须使用哪个散列表来自动排除空键或值,如果键或值为空或空 – user2684215

+0

@ user2684215取决于您想要实现的内容。你自己也很容易做到这一点。 – Thomas