<p>I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.</p>

<p>Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found.</p>

<p>In Perl, incrementing such a value would be trivially easy:</p>

<pre><code>$map{$word}++;
</code></pre>

<p>But in Java, it's much more complicated. Here the way I'm currently doing it:</p>

<pre><code>int count = map.containsKey(word) ? map.get(word) : 0;
map.put(word, count + 1);
</code></pre>

<p>Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead?</p>

<p>Update: I've done a test of several of the answers. See below.</p>

[{'answer_id': 81401, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 1, 'selected': False, 'text': '<p>The various primitive wrappers, e.g., <code>Integer</code> are immutable so there\'s really not a more concise way to do what you\'re asking <em>unless</em> you can do it with something like <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicLong.html" rel="nofollow noreferrer">AtomicLong</a>. I can give that a go in a minute and update. BTW, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html" rel="nofollow noreferrer">Hashtable</a> <em>is</em> a part of the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/collections/index.html" rel="nofollow noreferrer">Collections Framework</a>.</p>\n'}, {'answer_id': 81417, 'author': 'tovare', 'author_id': 12677, 'author_profile': 'https://Stackoverflow.com/users/12677', 'pm_score': 2, 'selected': False, 'text': '<p>There are a couple of approaches:</p>\n\n<ol>\n<li><p>Use a Bag alorithm like the sets contained in Google Collections.</p></li>\n<li><p>Create mutable container which you can use in the Map:</p></li>\n</ol>\n\n<pre>\n<code>\n    class My{\n        String word;\n        int count;\n    }\n</code>\n</pre>\n\n<p>And use put("word", new My("Word") ); Then you can check if it exists and increment when adding.</p>\n\n<p>Avoid rolling your own solution using lists, because if you get innerloop searching and sorting, your performance will stink. The first HashMap solution is actually quite fast, but a proper like that found in Google Collections is probably better.</p>\n\n<p>Counting words using Google Collections, looks something like this:</p>\n\n<pre>\n<code>\n\n    HashMultiset s = new HashMultiset();\n    s.add("word");\n    s.add("word");\n    System.out.println(""+s.count("word") );\n\n</code>\n</pre>\n\n<p>Using the HashMultiset is quite elegent, because a bag-algorithm is just what you need when counting words.</p>\n'}, {'answer_id': 81522, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 5, 'selected': False, 'text': '<p>As a follow-up to my own comment: Trove looks like the way to go. If, for whatever reason, you wanted to stick with the standard JDK, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentMap.html" rel="noreferrer">ConcurrentMap</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicLong.html" rel="noreferrer">AtomicLong</a> can make the code a <em>tiny</em> bit nicer, though YMMV.</p>\n<pre><code>    final ConcurrentMap&lt;String, AtomicLong&gt; map = new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n    map.putIfAbsent(&quot;foo&quot;, new AtomicLong(0));\n    map.get(&quot;foo&quot;).incrementAndGet();\n</code></pre>\n<p>will leave <code>1</code> as the value in the map for <code>foo</code>. Realistically, increased friendliness to threading is all that this approach has to recommend it.</p>\n'}, {'answer_id': 81550, 'author': 'Philip Helger', 'author_id': 15254, 'author_profile': 'https://Stackoverflow.com/users/15254', 'pm_score': 4, 'selected': False, 'text': '<p>Another way would be creating a mutable integer:</p>\n\n<pre><code>class MutableInt {\n  int value = 0;\n  public void inc () { ++value; }\n  public int get () { return value; }\n}\n...\nMap&lt;String,MutableInt&gt; map = new HashMap&lt;String,MutableInt&gt; ();\nMutableInt value = map.get (key);\nif (value == null) {\n  value = new MutableInt ();\n  map.put (key, value);\n} else {\n  value.inc ();\n}\n</code></pre>\n\n<p>of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.</p>\n'}, {'answer_id': 81722, 'author': 'Glever', 'author_id': 15504, 'author_profile': 'https://Stackoverflow.com/users/15504', 'pm_score': 3, 'selected': False, 'text': '<p>Instead of calling containsKey() it is faster just to call map.get and check if the returned value is null or not.</p>\n\n<pre><code>    Integer count = map.get(word);\n    if(count == null){\n        count = 0;\n    }\n    map.put(word, count + 1);\n</code></pre>\n'}, {'answer_id': 81765, 'author': 'Aleksandar Dimitrov', 'author_id': 11797, 'author_profile': 'https://Stackoverflow.com/users/11797', 'pm_score': 5, 'selected': False, 'text': '<p>You should be aware of the fact that your original attempt </p>\n\n<pre>int count = map.containsKey(word) ? map.get(word) : 0;</pre>\n\n<p>contains two potentially expensive operations on a map, namely <code>containsKey</code> and <code>get</code>. The former performs an operation potentially pretty similar to the latter, so you\'re doing the same work <em>twice</em>!</p>\n\n<p>If you look at the API for Map, <code>get</code> operations usually return <code>null</code> when the map does not contain the requested element.</p>\n\n<p>Note that this will make a solution like</p>\n\n<pre>map.put( key, map.get(key) + 1 );</pre>\n\n<p>dangerous, since it might yield <code>NullPointerException</code>s. You should check for a <code>null</code> first.\n<p><p>\n<b>Also note</b>, and this is very important, that <code>HashMap</code>s <em>can</em> contain <code>nulls</code> by definition. So not every returned <code>null</code> says "there is no such element". In this respect, <code>containsKey</code> behaves <em>differently</em> from <code>get</code> in actually telling you <em>whether</em> there is such an element. Refer to the API for details.\n<p><p>\nFor your case, however, you might not want to distinguish between a stored <code>null</code> and "noSuchElement". If you don\'t want to permit <code>null</code>s you might prefer a <code>Hashtable</code>. Using a wrapper library as was already proposed in other answers might be a better solution to manual treatment, depending on the complexity of your application.</p>\n\n<p>To complete the answer (and I forgot to put that in at first, thanks to the edit function!), the best way of doing it natively, is to <code>get</code> into a <code>final</code> variable, check for <code>null</code> and <code>put</code> it back in with a <code>1</code>. The variable should be <code>final</code> because it\'s immutable anyway. The compiler might not need this hint, but its clearer that way.</p>\n\n<pre>\nfinal HashMap map = generateRandomHashMap();\nfinal Object key = fetchSomeKey();\nfinal Integer i = map.get(key);\nif (i != null) {\n    map.put(i + 1);\n} else {\n    // do something\n}\n</pre>\n\n<p>If you do not want to rely on autoboxing, you should say something like <code>map.put(new Integer(1 + i.getValue()));</code> instead.</p>\n'}, {'answer_id': 81771, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 1, 'selected': False, 'text': "<p>I'd use Apache Collections Lazy Map (to initialize values to 0) and use MutableIntegers from Apache Lang as values in that map. </p>\n\n<p>Biggest cost is having to serach the map twice in your method. In mine you have to do it just once. Just get the value (it will get initialized if absent) and increment it.</p>\n"}, {'answer_id': 82423, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Are you sure that this is a bottleneck? Have you done any performance analysis?</p>\n\n<p>Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.</p>\n\n<p>Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.</p>\n'}, {'answer_id': 85007, 'author': 'volley', 'author_id': 13905, 'author_profile': 'https://Stackoverflow.com/users/13905', 'pm_score': 3, 'selected': False, 'text': '<p>Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.</p>\n\n<p>If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):</p>\n\n<pre><code>static class MutableInt {\n  int value = 1;\n  void inc() { ++value; }\n  int get() { return value; }\n}\n...\nMap&lt;String,MutableInt&gt; map = new HashMap&lt;String,MutableInt&gt;();\nMutableInt value = map.get(key);\nif (value == null) {\n  value = new MutableInt();\n  map.put(key, value);\n} else {\n  value.inc();\n}\n</code></pre>\n\n<p>If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned <a href="http://trove4j.sourceforge.net" rel="noreferrer">GNU Trove</a>.</p>\n\n<p>By the way, a good search term for this subject is "histogram".</p>\n'}, {'answer_id': 85342, 'author': 'Chris Nokleberg', 'author_id': 8902, 'author_profile': 'https://Stackoverflow.com/users/8902', 'pm_score': 5, 'selected': False, 'text': '<p>It\'s always a good idea to look at the <a href="http://code.google.com/p/google-collections/" rel="noreferrer">Google Collections Library</a> for this kind of thing. In this case a <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html" rel="noreferrer">Multiset</a> will do the trick:</p>\n\n<pre><code>Multiset bag = Multisets.newHashMultiset();\nString word = "foo";\nbag.add(word);\nbag.add(word);\nSystem.out.println(bag.count(word)); // Prints 2\n</code></pre>\n\n<p>There are Map-like methods for iterating over keys/entries, etc. Internally the implementation currently uses a <code>HashMap&lt;E, AtomicInteger&gt;</code>, so you will not incur boxing costs.</p>\n'}, {'answer_id': 107987, 'author': 'gregory', 'author_id': 10204, 'author_profile': 'https://Stackoverflow.com/users/10204', 'pm_score': 10, 'selected': True, 'text': '<h2>Some test results</h2>\n\n<p>I\'ve gotten a lot of good answers to this question--thanks folks--so I decided to run some tests and figure out which method is actually fastest. The five methods I tested are these:</p>\n\n<ul>\n<li>the "ContainsKey" method that I presented in <a href="https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java">the question</a></li>\n<li>the "TestForNull" method suggested by Aleksandar Dimitrov</li>\n<li>the "AtomicLong" method suggested by Hank Gay</li>\n<li>the "Trove" method suggested by jrudolph</li>\n<li>the "MutableInt" method suggested by phax.myopenid.com</li>\n</ul>\n\n<h2>Method</h2>\n\n<p>Here\'s what I did...</p>\n\n<ol>\n<li>created five classes that were identical except for the differences shown below. Each class had to perform an operation typical of the scenario I presented: opening a 10MB file and reading it in, then performing a frequency count of all the word tokens in the file. Since this took an average of only 3 seconds, I had it perform the frequency count (not the I/O) 10 times.</li>\n<li>timed the loop of 10 iterations but <em>not the I/O operation</em> and recorded the total time taken (in clock seconds) essentially using <a href="http://books.google.com/books?id=t85jM-ZwTX0C&amp;printsec=frontcover&amp;dq=java+cookbook&amp;sig=ACfU3U1lAe1vnbVUwdIcWeTpaxZi1xVUXQ#PPA734,M1" rel="noreferrer">Ian Darwin\'s method in the Java Cookbook</a>.</li>\n<li>performed all five tests in series, and then did this another three times.</li>\n<li>averaged the four results for each method.</li>\n</ol>\n\n<h2>Results</h2>\n\n<p>I\'ll present the results first and the code below for those who are interested.</p>\n\n<p>The <strong>ContainsKey</strong> method was, as expected, the slowest, so I\'ll give the speed of each method in comparison to the speed of that method.</p>\n\n<ul>\n<li><strong>ContainsKey:</strong> 30.654 seconds (baseline)</li>\n<li><strong>AtomicLong:</strong> 29.780 seconds (1.03 times as fast)</li>\n<li><strong>TestForNull:</strong> 28.804 seconds (1.06 times as fast)</li>\n<li><strong>Trove:</strong> 26.313 seconds (1.16 times as fast)</li>\n<li><strong>MutableInt:</strong> 25.747 seconds (1.19 times as fast)</li>\n</ul>\n\n<h2>Conclusions</h2>\n\n<p>It would appear that only the MutableInt method and the Trove method are significantly faster, in that only they give a performance boost of more than 10%. However, if threading is an issue, AtomicLong might be more attractive than the others (I\'m not really sure). I also ran TestForNull with <code>final</code> variables, but the difference was negligible.</p>\n\n<p>Note that I haven\'t profiled memory usage in the different scenarios. I\'d be happy to hear from anybody who has good insights into how the MutableInt and Trove methods would be likely to affect memory usage.</p>\n\n<p>Personally, I find the MutableInt method the most attractive, since it doesn\'t require loading any third-party classes. So unless I discover problems with it, that\'s the way I\'m most likely to go.</p>\n\n<h2>The code</h2>\n\n<p>Here is the crucial code from each method.</p>\n\n<h3>ContainsKey</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nMap&lt;String, Integer&gt; freq = new HashMap&lt;String, Integer&gt;();\n...\nint count = freq.containsKey(word) ? freq.get(word) : 0;\nfreq.put(word, count + 1);\n</code></pre>\n\n<h3>TestForNull</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nMap&lt;String, Integer&gt; freq = new HashMap&lt;String, Integer&gt;();\n...\nInteger count = freq.get(word);\nif (count == null) {\n    freq.put(word, 1);\n}\nelse {\n    freq.put(word, count + 1);\n}\n</code></pre>\n\n<h3>AtomicLong</h3>\n\n<pre><code>import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicLong;\n...\nfinal ConcurrentMap&lt;String, AtomicLong&gt; map = \n    new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n...\nmap.putIfAbsent(word, new AtomicLong(0));\nmap.get(word).incrementAndGet();\n</code></pre>\n\n<h3>Trove</h3>\n\n<pre><code>import gnu.trove.TObjectIntHashMap;\n...\nTObjectIntHashMap&lt;String&gt; freq = new TObjectIntHashMap&lt;String&gt;();\n...\nfreq.adjustOrPutValue(word, 1, 1);\n</code></pre>\n\n<h3>MutableInt</h3>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n...\nclass MutableInt {\n  int value = 1; // note that we start at 1 since we\'re counting\n  public void increment () { ++value;      }\n  public int  get ()       { return value; }\n}\n...\nMap&lt;String, MutableInt&gt; freq = new HashMap&lt;String, MutableInt&gt;();\n...\nMutableInt count = freq.get(word);\nif (count == null) {\n    freq.put(word, new MutableInt());\n}\nelse {\n    count.increment();\n}\n</code></pre>\n'}, {'answer_id': 855154, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 1, 'selected': False, 'text': '<p>The <a href="http://code.google.com/p/functionaljava" rel="nofollow noreferrer">Functional Java</a> library\'s <code>TreeMap</code> datastructure has an <code>update</code> method in the latest trunk head:</p>\n\n<pre><code>public TreeMap&lt;K, V&gt; update(final K k, final F&lt;V, V&gt; f)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>import static fj.data.TreeMap.empty;\nimport static fj.function.Integers.add;\nimport static fj.pre.Ord.stringOrd;\nimport fj.data.TreeMap;\n\npublic class TreeMap_Update\n  {public static void main(String[] a)\n    {TreeMap&lt;String, Integer&gt; map = empty(stringOrd);\n     map = map.set("foo", 1);\n     map = map.update("foo", add.f(1));\n     System.out.println(map.get("foo").some());}}\n</code></pre>\n\n<p>This program prints "2".</p>\n'}, {'answer_id': 4257986, 'author': 'the felis leo', 'author_id': 517668, 'author_profile': 'https://Stackoverflow.com/users/517668', 'pm_score': 2, 'selected': False, 'text': '<p>"put" need "get" (to ensure no duplicate key).<br>\nSo directly do a "put",<br>\nand if there was a previous value, then do an addition:</p>\n\n<pre><code>Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (1); // default = inc\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n  newValue.add(oldValue); // old + inc\n}\n</code></pre>\n\n<p>If count starts at 0, then add 1: (or any others values...)</p>\n\n<pre><code>Map map = new HashMap ();\n\nMutableInt newValue = new MutableInt (0); // default\nMutableInt oldValue = map.put (key, newValue);\nif (oldValue != null) {\n  newValue.setValue(oldValue + 1); // old + inc\n}\n</code></pre>\n\n<p><em>Notice :</em> This code is not thread safe. Use it to build then use the map, not to concurrently update it. </p>\n\n<p><em>Optimization :</em> In a loop, keep old value to become the new value of next loop.</p>\n\n<pre><code>Map map = new HashMap ();\nfinal int defaut = 0;\nfinal int inc = 1;\n\nMutableInt oldValue = new MutableInt (default);\nwhile(true) {\n  MutableInt newValue = oldValue;\n\n  oldValue = map.put (key, newValue); // insert or...\n  if (oldValue != null) {\n    newValue.setValue(oldValue + inc); // ...update\n\n    oldValue.setValue(default); // reuse\n  } else\n    oldValue = new MutableInt (default); // renew\n  }\n}\n</code></pre>\n'}, {'answer_id': 4283959, 'author': 'the felis leo', 'author_id': 521173, 'author_profile': 'https://Stackoverflow.com/users/521173', 'pm_score': 2, 'selected': False, 'text': '<p>Google Collections HashMultiset :<br>\n - quite elegant to use<br>\n - but consume CPU and memory</p>\n\n<p>Best would be to have a method like : <code>Entry&lt;K,V&gt; getOrPut(K);</code> \n(elegant, and low cost)</p>\n\n<p>Such a method will compute hash and index only once,\nand then we could do what we want with the entry\n(either replace or update the value).</p>\n\n<p>More elegant:<br>\n - take a <code>HashSet&lt;Entry&gt;</code><br>\n - extend it so that <code>get(K)</code> put a new Entry if needed<br>\n - Entry could be your own object.<br>\n--> <code>(new MyHashSet()).get(k).increment();</code>  </p>\n'}, {'answer_id': 11287489, 'author': "Eamonn O'Brien-Strain", 'author_id': 978525, 'author_profile': 'https://Stackoverflow.com/users/978525', 'pm_score': 2, 'selected': False, 'text': "<p>A variation on the MutableInt approach that might be even faster, if a bit of a hack, is to use a single-element int array: </p>\n\n<pre><code>Map&lt;String,int[]&gt; map = new HashMap&lt;String,int[]&gt;();\n...\nint[] value = map.get(key);\nif (value == null) \n  map.put(key, new int[]{1} );\nelse\n  ++value[0];\n</code></pre>\n\n<p>It would be interesting if you could rerun your performance tests with this variation.  It might be the fastest.</p>\n\n<hr>\n\n<p>Edit: The above pattern worked fine for me, but eventually I changed to use Trove's collections to reduce memory size in some very large maps I was creating -- and as a bonus it was also faster.</p>\n\n<p>One really nice feature is that the <code>TObjectIntHashMap</code> class has a single <code>adjustOrPutValue</code> call that, depending on whether there is already a value at that key, will either put an initial value or increment the existing value.  This is perfect for incrementing:</p>\n\n<pre><code>TObjectIntHashMap&lt;String&gt; map = new TObjectIntHashMap&lt;String&gt;();\n...\nmap.adjustOrPutValue(key, 1, 1);\n</code></pre>\n"}, {'answer_id': 12266382, 'author': 'H6.', 'author_id': 419863, 'author_profile': 'https://Stackoverflow.com/users/419863', 'pm_score': 5, 'selected': False, 'text': '<h2>Google <a href="https://github.com/google/guava" rel="noreferrer">Guava</a> is your friend...</h2>\n\n<p>...at least in some cases. They have this nice <a href="http://google.github.io/guava/releases/21.0/api/docs/index.html?com/google/common/util/concurrent/AtomicLongMap.html" rel="noreferrer"><em>AtomicLongMap</em></a>. Especially nice because you are dealing with <em>long</em> as value in your map.</p>\n\n<p>E.g.</p>\n\n\n\n<pre class="lang-java prettyprint-override"><code>AtomicLongMap&lt;String&gt; map = AtomicLongMap.create();\n[...]\nmap.getAndIncrement(word);\n</code></pre>\n\n<p>Also possible to add more then 1 to the value:</p>\n\n<pre class="lang-java prettyprint-override"><code>map.getAndAdd(word, 112L); \n</code></pre>\n'}, {'answer_id': 18792535, 'author': 'Craig P. Motlin', 'author_id': 23572, 'author_profile': 'https://Stackoverflow.com/users/23572', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using <a href="http://www.eclipse.org/collections/" rel="nofollow noreferrer">Eclipse Collections</a>, you can use a <code>HashBag</code>. It will be the most efficient approach in terms of memory usage and it will also perform well in terms of execution speed.</p>\n\n<p><code>HashBag</code> is backed by a <code>MutableObjectIntMap</code> which stores primitive ints instead of <code>Counter</code> objects. This reduces memory overhead and improves execution speed.</p>\n\n<p><code>HashBag</code> provides the API you\'d need since it\'s a <code>Collection</code> that also allows you to query for the number of occurrences of an item.</p>\n\n<p>Here\'s an example from the <a href="https://github.com/eclipse/eclipse-collections-kata" rel="nofollow noreferrer">Eclipse Collections Kata</a>.</p>\n\n<pre><code>MutableBag&lt;String&gt; bag =\n  HashBag.newBagWith("one", "two", "two", "three", "three", "three");\n\nAssert.assertEquals(3, bag.occurrencesOf("three"));\n\nbag.add("one");\nAssert.assertEquals(2, bag.occurrencesOf("one"));\n\nbag.addOccurrences("one", 4);\nAssert.assertEquals(6, bag.occurrencesOf("one"));\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>\n'}, {'answer_id': 25354509, 'author': 'leventov', 'author_id': 648955, 'author_profile': 'https://Stackoverflow.com/users/648955', 'pm_score': 6, 'selected': False, 'text': '<p>A little research in 2016: <a href="https://github.com/leventov/java-word-count" rel="noreferrer">https://github.com/leventov/java-word-count</a>, <a href="https://github.com/leventov/java-word-count/blob/8a12a5ea4f53f01b9ee0e57f8aec70d75bc2030d/src/jmh/java/com/koloboke/wordcount/WordCount.java" rel="noreferrer">benchmark source code</a></p>\n\n<p>Best results per method (smaller is better):</p>\n\n<pre><code>                 time, ms\nkolobokeCompile  18.8\nkoloboke         19.8\ntrove            20.8\nfastutil         22.7\nmutableInt       24.3\natomicInteger    25.3\neclipse          26.9\nhashMap          28.0\nhppc             33.6\nhppcRt           36.5\n</code></pre>\n\n<p>Time\\space results:\n<img src="https://i.stack.imgur.com/nR5yp.png" width="600"></p>\n'}, {'answer_id': 33711386, 'author': 'off99555', 'author_id': 2593810, 'author_profile': 'https://Stackoverflow.com/users/2593810', 'pm_score': 6, 'selected': False, 'text': '<pre><code>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();\nString key = "a random key";\nint count = map.getOrDefault(key, 0); // ensure count will be one of 0,1,2,3,...\nmap.put(key, count + 1);\n</code></pre>\n\n<p>And that\'s how you increment a value with simple code.</p>\n\n<p>Benefit:</p>\n\n<ul>\n<li>No need to add a new class or use another concept of mutable int</li>\n<li>Not relying on any library</li>\n<li>Easy to understand what\'s going on exactly (Not too much abstraction)</li>\n</ul>\n\n<p>Downside:</p>\n\n<ul>\n<li>The hash map will be searched twice for get() and put(). So it will not be the most performant code. </li>\n</ul>\n\n<p>Theoretically, once you call get(), you already know where to put(), so you should not have to search again. But searching in hash map usually takes a very minimal time that you can kind of ignore this performance issue.</p>\n\n<p>But if you are very serious about the issue, you are a perfectionist, another way is to use merge method, this is (probably) more efficient than the previous code snippet as you will be (theoretically) searching the map only once: (though this code is not obvious from first sight, it\'s short and performant)</p>\n\n<pre><code>map.merge(key, 1, (a,b) -&gt; a+b);\n</code></pre>\n\n<p>Suggestion: you should care about code readability more than little performance gain in most of the time. If the first code snippet is easier for you to understand then use it. But if you are able to understand the 2nd one fine then you can also go for it!</p>\n'}, {'answer_id': 37296257, 'author': 'MGoksu', 'author_id': 3721429, 'author_profile': 'https://Stackoverflow.com/users/3721429', 'pm_score': 1, 'selected': False, 'text': '<p>I don\'t know how efficient it is but the below code works as well.You need to define a <code>BiFunction</code> at the beginning. Plus, you can make more than just increment with this method.</p>\n\n<pre><code>public static Map&lt;String, Integer&gt; strInt = new HashMap&lt;String, Integer&gt;();\n\npublic static void main(String[] args) {\n    BiFunction&lt;Integer, Integer, Integer&gt; bi = (x,y) -&gt; {\n        if(x == null)\n            return y;\n        return x+y;\n    };\n    strInt.put("abc", 0);\n\n\n    strInt.merge("abc", 1, bi);\n    strInt.merge("abc", 1, bi);\n    strInt.merge("abc", 1, bi);\n    strInt.merge("abcd", 1, bi);\n\n    System.out.println(strInt.get("abc"));\n    System.out.println(strInt.get("abcd"));\n}\n</code></pre>\n\n<p>output is</p>\n\n<pre><code>3\n1\n</code></pre>\n'}, {'answer_id': 37439971, 'author': 'akhil_mittal', 'author_id': 1216775, 'author_profile': 'https://Stackoverflow.com/users/1216775', 'pm_score': 4, 'selected': False, 'text': '<p>You can make use of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-" rel="noreferrer">computeIfAbsent</a> method in <code>Map</code> interface provided in <strong>Java 8</strong>. </p>\n\n<pre><code>final Map&lt;String,AtomicLong&gt; map = new ConcurrentHashMap&lt;&gt;();\nmap.computeIfAbsent("A", k-&gt;new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent("B", k-&gt;new AtomicLong(0)).incrementAndGet();\nmap.computeIfAbsent("A", k-&gt;new AtomicLong(0)).incrementAndGet(); //[A=2, B=1]\n</code></pre>\n\n<p>The method <code>computeIfAbsent</code> checks if the specified key is already associated with a value or not? If no associated value then it attempts to compute its value using the given mapping function. In any case it returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.</p>\n\n<p>On a side note if you have a situation where multiple threads update a common sum you can have a look at <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/LongAdder.html" rel="noreferrer">LongAdder</a> class.Under high contention, expected throughput of this class is significantly higher than <code>AtomicLong</code>, at the expense of higher space consumption.</p>\n'}, {'answer_id': 42648785, 'author': 'LE GALL Benoît', 'author_id': 244911, 'author_profile': 'https://Stackoverflow.com/users/244911', 'pm_score': 9, 'selected': False, 'text': '<p>Now there is a shorter way with Java 8 using <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#merge(K,V,java.util.function.BiFunction)" rel="noreferrer"><code>Map::merge</code></a>. </p>\n\n<pre><code>myMap.merge(key, 1, Integer::sum)\n</code></pre>\n\n<p>What it does:</p>\n\n<ul>\n<li>if <em>key</em> do not exists, put <em>1</em> as value</li>\n<li>otherwise <em>sum 1</em> to the value linked to <em>key</em></li>\n</ul>\n\n<p>More information <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-" rel="noreferrer">here</a>.</p>\n'}, {'answer_id': 48715920, 'author': 'Keith', 'author_id': 43370, 'author_profile': 'https://Stackoverflow.com/users/43370', 'pm_score': -1, 'selected': False, 'text': '<p>Since a lot of people search Java topics for Groovy answers, here\'s how you can do it in Groovy:</p>\n\n<pre><code>dev map = new HashMap&lt;String, Integer&gt;()\nmap.put("key1", 3)\n\nmap.merge("key1", 1) {a, b -&gt; a + b}\nmap.merge("key2", 1) {a, b -&gt; a + b}\n</code></pre>\n'}, {'answer_id': 54507230, 'author': 'ggaugler', 'author_id': 10429757, 'author_profile': 'https://Stackoverflow.com/users/10429757', 'pm_score': -1, 'selected': False, 'text': "<p>Hope I'm understanding your question correctly, I'm coming to Java from Python so I can empathize with your struggle. </p>\n\n<p>if you have</p>\n\n<pre><code>map.put(key, 1)\n</code></pre>\n\n<p>you would do</p>\n\n<pre><code>map.put(key, map.get(key) + 1)\n</code></pre>\n\n<p>Hope this helps!</p>\n"}, {'answer_id': 55341335, 'author': 'sudoz', 'author_id': 4305743, 'author_profile': 'https://Stackoverflow.com/users/4305743', 'pm_score': 3, 'selected': False, 'text': '<p>Quite simple, just use the built-in function in <code>Map.java</code> as followed</p>\n\n<pre class="lang-java prettyprint-override"><code>map.put(key, map.getOrDefault(key, 0) + 1);\n</code></pre>\n'}, {'answer_id': 56712619, 'author': 'Assaduzzaman Assad', 'author_id': 9809339, 'author_profile': 'https://Stackoverflow.com/users/9809339', 'pm_score': -1, 'selected': False, 'text': '<p>The simple and easy way in java 8 is the following:</p>\n\n<pre><code>final ConcurrentMap&lt;String, AtomicLong&gt; map = new ConcurrentHashMap&lt;String, AtomicLong&gt;();\n    map.computeIfAbsent("foo", key -&gt; new AtomicLong(0)).incrementAndGet();\n</code></pre>\n'}, {'answer_id': 57838567, 'author': 'Eugene Chung', 'author_id': 968152, 'author_profile': 'https://Stackoverflow.com/users/968152', 'pm_score': 3, 'selected': False, 'text': "<p>I suggest to use Java 8 Map::compute().\nIt considers the case when a key doesn't exist, too.</p>\n\n<pre><code>Map.compute(num, (k, v) -&gt; (v == null) ? 1 : v + 1);\n</code></pre>\n"}, {'answer_id': 68159505, 'author': 'Sarvar N', 'author_id': 2490074, 'author_profile': 'https://Stackoverflow.com/users/2490074', 'pm_score': 1, 'selected': False, 'text': '<p>Counting using streams and <code>getOrDefault</code>:</p>\n<pre><code>String s = &quot;abcdeff&quot;;\ns.chars().mapToObj(c -&gt; (char) c)\n .forEach(c -&gt; {\n     int count = countMap.getOrDefault(c, 0) + 1;\n     countMap.put(c, count);\n  });\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/81346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10204/']