Skip to content


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:

CODE:
  1. class MutableInt {
  2.   int value = 0;
  3.   public void inc () { ++value; }
  4.   public int get () { return value; }
  5. }
  6.  
  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. } else {
  13.   value.inc ();
  14. }

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

Posted in Algorithms, Computer Science, Culture, Data Structures, Disciplines, Java, Languages, Tips, Hacks, & Tricks. Tagged with , , , , , , .

3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Have you looked at java.util.concurrent.atomic.AtomicInteger? It's part of Java 5 and up I believe. It has methods for both incrementing and retrieving values much the way the MutableInt class you've created does.

  2. Matthew,

    I haven't looked at that before, but good find.. seems like there were a lot of minor enhancements in Java 5 that I forget about.

  3. Dead Beef said

    It may be fast, but it's not thread-safe. You're aware of this, right?

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.