Map.merge

written in collections, java, java8, jdk8, map

Sometimes is the small things… Like finding a new method that does exactly what you were needing.

Let’s say I’m trying to build a book index. In case you haven’t touch an actual, physical, dead-tree book in a while here’s what an index looks like1:

One way of doing this would be to build a map of: terms to a list of comma separated pages. This is, by no means, the best way of modeling an index, but it’ll serve our purpose of illustrating the Map.merge method.

Up until yesterday I’d have written such code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Index {
  private final Map<String, String> termToPagesMap = new HashMap<>();
  
  public void addWord(String term, int page) {
      final String newPage = String.valueOf(page);
      final String pages = termToPagesMap.get(term);
      if (pages == null) {
          termToPagesMap.put(term, newPage);
      } else {
          termToPagesMap.put(term, pages.concat(", " + newPage));
      }
  }
}

But today I know better! With Map.merge I can achieve the same result in just 1 line:

1
2
3
4
5
6
7
public class Index {
  private final Map<String, String> termToPagesMap = new HashMap<>();
  
  public void addWord(String term, int page) {
          termToPagesMap.merge(term, String.valueOf(page), (pages, newPage) -> pages.concat(", " + newPage));
  }
}

Basically we provide:

  • The entry key
  • A value to be used if there was no associated value to the key (or it was null)
  • A  remapping function that takes the old value, the new value and calculates the new value for the map

Bonus track: Removal

There’s one more trick you can do with Map.merge. Citing the documentation:

If the function returns null the mapping is removed

Something to keep in mind in case it comes in handy in the future. Or if you find yourself debugging an issue of ”vanishing entries on a Map”, then maybe you should check your  remapping function 😉


  1. I’m aware that ebooks have indexes too, but who the fuck uses them when you can do a full blown text search


Comments