Skip to main content

Posts

Showing posts from March, 2019

Map.merge() - One method to rule them all

Russian translation available: Map.merge () - метод, чтобы управлять всеми остальными

I don’t often explain a single method in JDK, but when I do, it’s about Map.merge(). Probably the most versatile operation in the key-value universe. And also rather obscure and rarely used. merge() can be explained as follows: it either puts new value under the given key (if absent) or updates existing key with a given value (UPSERT). Let’s start with the most basic example: counting unique word occurrences. Pre-Java 8 (read: pre-2014!) code was quite messy and the essence was lost in implementation details:

var map = new HashMap<String, Integer>(); words.forEach(word -> { var prev = map.get(word); if (prev == null) { map.put(word, 1); } else { map.put(word, prev + 1); } }); However, it works and for given input produces desired output:

var words = List.of("Foo", "Bar", "Foo", "Buzz", "Foo", "Buzz", &…