how to merge more than one hashmaps also sum the values of same key in java

前端 未结 8 1562
清歌不尽
清歌不尽 2021-02-13 03:03

ı am trying to merge more than one hashmaps also sum the values of same key, ı want to explain my problem with toy example as follows

    HashMap

        
8条回答
  •  终归单人心
    2021-02-13 03:31

    If the key exists, add to it's value. If not insert.

    Here is a simple example which merges one map into another:

    Foo oldVal = map.get(key);
    if oldVal == null
    {
       map2.put(key, newVal);
    }
    else
    {
       map2.put(key, newVal + oldVal);
    }
    

    Obviously you have to loop over the first map so you can process all of it's entries but that's trivial.

提交回复
热议问题