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 org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;

public class MapMergeTest {

    @Test
    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
        map.remove(key);
    } else {
    if (newValue != null)
        map.put(key, newValue);
    else
        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: airhacks.io.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License