Custom Map Updates without Null Checks: Map#merge 📎
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.