Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment an Integer within a HashMap

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)++; 
like image 690
NimChimpsky Avatar asked Nov 25 '10 13:11

NimChimpsky


People also ask

How does HashMap increase value by 1?

Map<String, Integer> map = new HashMap<>(); String key = "a random key"; int count = map. getOrDefault(key, 0); // ensure count will be one of 0,1,2,3,... map. put(key, count + 1);

Can HashMap have integer keys?

It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.

Can we update HashMap value?

You can change either the key or the value in your hashmap, but you can't change both at the same time.


1 Answers

This is the shortest code that does this job.

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

I think it is not too long.

like image 58
AlexR Avatar answered Oct 02 '22 14:10

AlexR