HashMap value auto increment

Tags: ,



when I was coding, one question occurred to me, which is if the value part(Integer) in the HashMap is able to auto-increment in the following scenario?

Map<String, Integer> dictionary = new HashMap<String, Integer>();    
dictionary.put("a",1);
dictionary.put("b",1);

Answer

Consider using an AtomicInteger:

Map<Key, AtomicInteger> dictionary =
  new HashMap<String, AtomicInteger>();

dictionary.get(key).incrementAndGet();

Also consider using a for loop to simplify the code.



Source: stackoverflow