I am seaching for a data structure that is almost exactly a HashMap<String,Integer>, but the problem with HashMaps is that most of the data stored in key value pairs is lost by calling the putAll() method on two HashMaps, due to the replacement behavior of putVal() in line 655 of the java/util/HashMap.java.
This is basically the change that I want:
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
-- e.value = value;
++ e.value = value + oldValue;
afterNodeAccess(e);
return oldValue;
}
Is there an existing data structure, that I've overlooked that would do such a thing, or how do I create a class that is basically a HashMap with that one change?
I've already tried to code something, but doen't work how I want it to... In fact it doen't matter if I set the put method on @Override, do it like that, or delete it completely - the replacing behavior ofcourse stays the same, because putAll() uses putVal() that I can't reach / change from the outside - or I at least don't know how...
/**
* doesn't work, putAll() uses putVal() that I can't reach
*/
public class SumHashMap<K> extends HashMap<K, Integer> {
private static final long serialVersionUID = 1L;
public Integer put(K key, Integer value) {
Integer oldValue = get(key);
if (oldValue == null)
return super.put(key, value);
return super.put(key, oldValue + value);
}
}
Thanks in advance
Additional info:
- I want to use the putAll() function in the reduction of a stream out of custom HashMaps.
- If I have two custom HashMaps of this sort
{"key1" : 2, "key3" : 4}and{"key3" : 1}the result ofa.putAll(b)should be{"key1" : 2, "key3" : 5}
putfunction a static helper function. Data structures are made to be generic. It would be unmaintainable when you'll have to create a new hashmap class with a slight variation.