Increment an Integer within a HashMap

You can use a mutable integer such as AtomicInteger.

Map<Key, AtomicInteger> myMap = new HashMap<Key, AtomicInteger>();
myMap.get(key).incrementAndGet();

Or you can use Trove4j which supports primitives in collections.

TObjectIntHashMap<Key> myMap;
myMap.increment(key); 

This is the shortest code that does this job.

myMap.put(key, myMap.get(key) + 1)

I think it is not too long.


Do I have to return the object and then put a new one in ?

As long as you use the Integer wrapper class yes, because it's immutable. You could use a mutable wrapper class instead, even one that has an increment() method. However, you then lose the ability to use autoboxing and autounboxing on the values.


In Java 8 there are new methods on Map which you can use with lambdas to solve this. First alternative, compute:

a.compute(key, (k, v) -> v+1);

Note that this only works if the hash is initialized for all possible keys.

If this is not guaranteed you can either change the above code to:

a.compute(key, (k, v) -> v == null ? 1 : v + 1);

Or use the merge method (which I would prefer):

a.merge(key, 1, (a, b) -> a + b);

Maybe there are more lambda based methods I am not aware of.