I feel the merge(key, value, BiFunction) introduced in Map in Java 8 is the most versatile method I have ever come across. It takes in the key, new value, and a mapping function to recalculate the value for the key if an existing mapping exists. It returns the new value associated with the specified key.

Suppose you had keys as strings and their values as integers and you wanted to increment the value for a key.

Map<String, Integer> map = new HashMap<>();
String key = "customer_1";
map.put(key, 4);

Here is how would you do without merge,

if (map.containsKey(key)) {
  int oldVal = map.get(key);
  int newVal = oldVal + 1;
  map.put(key, newVal);
} else {
  map.put(key, 1);

Verbose, isn’t it? Here is how would you use merge.

map.merge(key, 1, Integer::sum);

I have used method references which are compact and easy to read. Using lambda expressions,

map.merge(key, 1, (oldVal, newVal) -> oldVal + 1);

I like to read the method as map.merge(key, newVal, (oldVal, newVal) -> {remap}). The remapping function can be used in many ways,

  • merge the two values,(oldVal, newVal) -> old + newVal
  • simply overwrite the old value (oldVal, newVal) -> newVal
  • keep the old value instead (oldVal, newVal) -> oldVal
  • remove the old value (oldVal, newVal) -> null
  • replace with a constant (oldVal, newVal) -> k