The Most Efficent Way to Increment A Map Value in Java

Finding myself in a situation of needing to increment values in a map in Java, I was curious to see what the most efficient way to do so. Said piece of code will be looped over thousands of times and I wanted it to run as quickly possible. Yes, I know that pre-optimization is the root of all evil, but in this case it was something I needed to be conscious of.

I found a question/thread on StackOverflow where someone else had already pondered the same thing and got a long list of possible answers to compare to each other, including using Apache Commons and the Google Collections Library. After testing all of them, the fastest way ended-up being implementing a “MutableInt” class and using it as the value data type in the map:

  1. class MutableInt {
  2.   int value = 0;
  3.   public void inc () { ++value; }
  4.   public int get () { return value; }
  5. }
  7. Map<string ,MutableInt> map = new HashMap<string ,MutableInt>();
  8. MutableInt value = map.get (key);
  9. if (value == null) {
  10.   value = new MutableInt ();
  11.   map.put (key, value);
  12. }
  14. ();

Pretty interesting stuff! Note that the above code snippet is not very cleanly formatted, but you’ll get the idea.

This entry was posted in Culture, Languages, Tips, Hacks, & Tricks and tagged , , , , , , . Bookmark the permalink.

6 Responses to "The Most Efficent Way to Increment A Map Value in Java"

Leave a reply