Word counter in Java is one line

Counting words is often used. Before Java 8, it can be something like this:

Map<String, Integer> counter = new HashMap<>();
 
//before Java 8
for (String word : words) {
    if (counter.containsKey(word)) {
        counter.put(word, counter.get(word) + 1);
    } else {
        counter.put(word, 1);
    }
}

After Java 8, it can be:

words.forEach(word -> {
    counter.putIfAbsent(word, 0);
    counter.compute(word, (w, count) -> count + 1);
});

If we remove the putIfAbsent() method, it's one line.

words.forEach(word -> counter.compute(word, (w, count) -> count == null ? 1 : count + 1));

With the map.merge() method, it is not only one line, but a short line.

words.forEach(word -> counter.merge(word, 1, (count, one) -> count + one));

And it can be even shorter.

words.forEach(word -> counter.merge(word, 1, Integer::sum));
Category >> Java >> Lambda Expression  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>