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)++;
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);
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.
You can change either the key or the value in your hashmap, but you can't change both at the same time.
This is the shortest code that does this job.
myMap.put(key, myMap.get(key) + 1)
I think it is not too long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With