Java HashMap Create or Increment Value

If you are using a HashMap to keep a running total of a series of elements, then you often need to increment a HashMap item, but if it doesn’t exist in the map yet, then you need to rather create it.

There are a number of ways to do this, let’s explore some of these.

Using Merge and Sum in Java 8

My absolute favourite is to use Java 8’s ability to do the below:

myMap.merge(key, 1, Integer::sum)

This will create a new one with the specified value if it does not exist, otherwise it will add sum the value with the newly added value.

Pre Java 8 solution

Pre Java 8, a nice way to do this is as follows:

Map<String, Integer> myMap = new HashMap<>();
String key = "your_key";
int count = myMap.getOrDefault(key, 0);
myMap.put(key, count + 1);

This can be simplified to:

myMap.put(key, myMap.getOrDefault(key, 0) + 1);

Some alternatives may include

ContainsKey

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> freq = new HashMap<String, Integer>();

int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);

TestForNull

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> freq = new HashMap<String, Integer>();

Integer count = freq.get(word);
if (count == null) freq.put(word, 1);
else freq.put(word, count + 1);

AtomicLong

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();

map.putIfAbsent(word, new AtomicLong(0));
map.get(word).incrementAndGet();

Trove

import gnu.trove.TObjectIntHashMap;

TObjectIntHashMap<String> freq = new TObjectIntHashMap<String>();

freq.adjustOrPutValue(word, 1, 1);

MutableInt

import java.util.HashMap;
import java.util.Map;

class MutableInt {
  int value = 1;
  public void increment () { ++value;      }
  public int  get ()       { return value; }
}

Map<String, MutableInt> freq = new HashMap<String, MutableInt>();

MutableInt count = freq.get(word);
if (count == null)freq.put(word, new MutableInt());
else count.increment();
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments