In C++ if I declare a map like std::map m
then I can increment the value for a specific key in the map in this way
m[key]++
In Java I declare a map
Map<Integer, Integer> m = new HashMap<>();
and I increment the value for a specific key in this way:
m.put(key, m.get(key).intValue() + 1)
My question: Is there any shortcut or better way to do this?
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
instead of using putIfAbsent on main map, just use compute function (and do everything inside that function, even the inner map stuff). Whatever you do inside the function will be thread-safe if using ConcurrentHashMap in the root map; no need for synchronization block if you do it this way.
There are two ways to use the increment operator; prefix and postfix increment. The prefix increment looks like ++variablename; while the postfix increment looks like variablename++; . Both of these operations add one to the value in the variable. The difference between the two is the order of how it works.
There is a problem with the accepted answer that if there is no value for a requested key, we'll get an exception. Here are a few ways to resolve the issue using Java 8 features:
Map.merge()
m.merge(key, 1, Integer::sum)
If the key doesn't exist, put 1 as value, otherwise sum 1 to the value given for the key.
Map.putIfAbsent()
m.putIfAbsent(key, 1);
m.put(key, m.get(key) + 1);
Similar to other answers, but clearly says you need to init the value first.
Map.compute()
m.compute(key, (k, v) -> v == null ? 1 : v + 1)
Always computing the value, providing 1 if there is nothing there yet.
Map.getOrDefault()
m.put(key, m.getOrDefault(key, 0) + 1)
Gets the value if it exists or a default value otherwise, and returns that value plus one.
You could use compute (Java 8+):
m.compute(key, (k, v) -> v + 1);
I've always preferred to use a mutable int for these problems. So the code ends up looking like...
m.get(key).increment()
This avoids the unnecessary put overhead (which is small).
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