开发者

Efficient way to subtract values in two HashMaps by key

开发者_运维知识库I am wondering how to efficiently subtract the values of two maps when their keys match. Currently I have 2 HashMap<String,Integer> and do it like this:

for (String key: map1.keySet()){
   if (map2.keySet().contains(key)){
       //subtract
   }
}

Is there a better way to do it?


Theoretically speaking, this is about as fast as it can be done unless you can somehow do a faster than O(n) way of finding the matching keys between the two HashMaps.

  • Iterate over keys in first map's keySet() - O(n)
    • See if key is in other map - O(1)
    • Do your operation - O(1)


Realise this is an old thread but do check out guava from google

https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps

You can use Map.difference and then get the entries in common, only in left, right etc.


I think there isn't a better method unless you use a different approach, and/or different data structures. You can for example create a class named ValuePair that can contain (up to) two values, which represent the values you are currently storing in two different maps, but you instead store all the pairs in a single map, and when it comes to "subtract" you can iterate in a single set of keys. Please note that a pair can be incomplete, so that no subtraction is done.

But that's probabily overkill.


have you considered using Apache Commons Collections?

CollectionUtils.subtract( collection1, collection2 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜