代码之家  ›  专栏  ›  技术社区  ›  user2684215

java HashMap密钥与低吞吐量的比较

  •  0
  • user2684215  · 技术社区  · 11 年前

    我想用otherMap检查origMap的键。如果找到了,就把otherMap的值作为键,origMap值作为值

    将其放入新的hashmap中。如果没有找到,则使用Bigdecimal将origmap的所有值放在与键“other”相同的映射中,并将值作为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);
    }
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Thomas    11 年前

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

    因为你似乎试图检查是否有 me.getKey() 在里面 otherMap 尝试 otherMap.get(me.getKey()) != null otherMap.containsKey(me.getKey()=) 相反

    此外, otherMap.get(key).equals(me.getKey()) 在你的情况下永远不会是真的(独立于 key ),因为您正在比较 其他地图 使用来自的密钥 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);
    }
    

    顺便说一句,为什么 原始地图 其他地图 类型为 Map<String, Object> 如果所有值都是字符串?那样的话 Map<String, String> 将更适合,从而消除了对 到字符串() 调用(以及null检查)。