Increment an Integer within a HashMap

53,337

Solution 1

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.

Solution 2

This is the shortest code that does this job.

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

I think it is not too long.

Solution 3

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.

Solution 4

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); 

Solution 5

You can't directly increment it, because it is immutable. You have to increment it and put the new object back.

Auto boxing is also interfering here. In fact what's happening is something similar to:

Integer i1 = getFromMap();
i1 = Integer.valueOf(++ i1.intValue());

So here your reference points to a new object. You have to put that object back in the map, under the same key.

Share:
53,337
NimChimpsky
Author by

NimChimpsky

side hustle : metriculous.network Spring is too bloated, I created my own web app framework Infrequent tweets What if programming languages were methods to eat an orange?

Updated on May 03, 2020

Comments

  • NimChimpsky
    NimChimpsky about 4 years

    Do I have to return the object and then put a new one in ? Or can I just directly increment ?

    Integer temp = myMap.get(key);
    temp++;
    myMap.put(key, temp);
    

    there is no way to just do this (this doesn't work) :

    myMap.get(key)++;