Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment value for a specific key in a Map in java?

Tags:

java

map

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?

like image 745
seal Avatar asked Nov 15 '14 11:11

seal


People also ask

How do I change the value of a key in a Java map?

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.

How do you increment a value inside a map in thread safe?

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.

How do you increment a variable in Java?

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.


3 Answers

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:

  1. Using 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.

  1. Using 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.

  1. Using Map.compute()

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

Always computing the value, providing 1 if there is nothing there yet.

  1. Using 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.

like image 155
Gaket Avatar answered Oct 21 '22 16:10

Gaket


You could use compute (Java 8+):

m.compute(key, (k, v) -> v + 1);
like image 20
Alex - GlassEditor.com Avatar answered Oct 21 '22 16:10

Alex - GlassEditor.com


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

like image 29
Andrew White Avatar answered Oct 21 '22 15:10

Andrew White