mercredi 4 mars 2015

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



ı 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<String, Integer> m = new HashMap<>();
HashMap<String, Integer> m2 = new HashMap<>();

m.put("apple", 2);
m.put("pear", 3);
m2.put("apple", 9);
m2.put("banana", 6);


ı tried putall


m.putAll(m2);


output is as follows {banana=6, apple=9, pear=3}


but its result is not true for this problem. ı want to output as


{banana=6, apple=11, pear=3}


how can ı get this result in java?




Aucun commentaire:

Enregistrer un commentaire