Say I have a map like
{one=1; two=1; three=1}
and another map like
{one=4; two=4; three=4}
I know that putAll() would add unique keys and replace existing keys.
Will it be possible to do an addition of both the maps which would produce a result like adding the values whenever there is an existing keyword.
{one=5; two=5; three=5}
Extend the HashMap and override the putAll method.
public class MyMap extends java.util.HashMap{
@Override
public void putAll(java.util.Map mapToAdd){
java.util.Iterator iterKeys = keySet().iterator();
while(iterKeys.hasNext()){
String currentKey = (String)iterKeys.next();
if(mapToAdd.containsKey(currentKey)){
mapToAdd.put(currentKey, new Integer(Integer.parseInt(get(currentKey).toString()) + Integer.parseInt(mapToAdd.get(currentKey).toString())));
}else{
mapToAdd.put(currentKey, get(currentKey));
}
}
super.putAll(mapToAdd);
}
public static void main(String args[]){
MyMap m1 = new MyMap();
m1.put("One", new Integer(1));
m1.put("Two", new Integer(2));
m1.put("Three", new Integer(3));
MyMap m2 = new MyMap();
m2.put("One", new Integer(4));
m2.put("Two", new Integer(5));
m2.put("Three", new Integer(6));
m1.putAll(m2);
System.out.println(m1);
}
}
Now, create objects of MyMap instead of HashMap. Created a fiddle Here
try this ,
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> map1 = new HashMap<String, Integer>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 1);
map.put("three", 1);
map1.put("one", 4);
map1.put("two", 4);
map1.put("three", 4);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(map1.get(entry.getKey())+entry.getValue());
map2.put(entry.getKey(),map1.get(entry.getKey())+entry.getValue());
}
Create a new Map
, then for all entries x
in map1
, if map2
contains key x
, put the addition of both values into the new map with key x
.
Try this method. Works with a generic key type. Value type remains Integer
as we are adding them.
public <K> void putAndAdd(Map<K, Integer> to,
Map<? extends K, ? extends Integer> from) {
for (Iterator<? extends Map.Entry<? extends K, ? extends Integer>> i = from
.entrySet().iterator(); i.hasNext();) {
Map.Entry<? extends K, ? extends Integer> e = i.next();
if (to.get(e.getKey()) != null) {
to.put(e.getKey(), to.get(e.getKey()) + e.getValue());
} else {
to.put(e.getKey(), e.getValue());
}
}
}