Custom Map Updates without Null Checks: Map#merge

The Java 1.8+ Map#merge method is useful for upserts of a Map with custom bevavior. Null checks are not required:

import java.util.HashMap;
import java.util.Map;
import static;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;

public class MapMergeTest {

    public void mergeInMap() {
        Map<String, Integer> map = new HashMap<>();
        int initial = 1;
        int result = map.merge("key", initial, (oldValue, newValue) -> oldValue + newValue);
        assertThat(result, is(1));

        int update = 42;
        int expected = initial + update;
        result = map.merge("key", update, (oldValue, newValue) -> oldValue + newValue);
        assertThat(result, is(expected));

The Map#merge is equivalent to:

if (oldValue != null ) {
    if (newValue != null)
        map.put(key, newValue);
    } else {
    if (newValue != null)
        map.put(key, newValue);
        return null;

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:


The equivalent old style version has to add oldValue and NewValue together when oldValue is not equal to Null

Posted by Werner on October 17, 2019 at 08:40 AM CEST #

The BiFunction in Map::merge can be substituted with Integer::sum method reference in this case, for further code amount reduction. But it might be opinion based.

Posted by Michał on October 17, 2019 at 10:09 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments