Master Java 8 Map Enhancements: Simplify Code with getOrDefault, computeIfAbsent, and merge
This tutorial shows how Java 8's new Map methods—getOrDefault, computeIfAbsent, and merge—can replace verbose null‑checking patterns, prevent NullPointerExceptions, and make common tasks like grouping values or counting words concise and readable.
JDK 8 introduced many useful Map methods that can greatly simplify code.
Many projects still use old patterns, resulting in verbose code and potential NullPointerExceptions.
Preventing NullPointerExceptions
Traditional code checks for null before processing map values, which is cumbersome.
<code>Map<String, String> map = new HashMap();
map.put("public", "xxx");
// possible NPE
System.out.println(map.get("pay").toUpperCase());</code>Using Objects.isNull or the ternary operator can reduce boilerplate, but JDK 8’s
Map#getOrDefaultdoes it in one line.
<code>String value = map.getOrDefault("pay", "");
System.out.println(value.toUpperCase());</code>For pre‑JDK 8 environments, Apache Commons‑Lang3
MapUtils.getStringprovides similar functionality.
<code>String value = MapUtils.getString(map, "pay", "");</code>Using computeIfAbsent
When a key should map to a collection, the classic approach requires explicit null checks.
<code>Map<String, List<String>> map = new HashMap();
List<String> list = map.get("javaFramework");
if (list == null) {
list = new ArrayList<>();
list.add("Spring");
map.put("javaFramework", list);
} else {
list.add("Spring");
}</code>JDK 8’s
computeIfAbsentreplaces this with a single statement.
<code>map.computeIfAbsent("javaFramework", k -> new ArrayList<>()).add("Spring");</code> putIfAbsentbehaves differently and can still return null, so it should not be used for this pattern.
Word Count with Map.merge
Counting word occurrences traditionally involves manual null checks and updates.
<code>Map<String, Integer> countMap = new HashMap();
Integer count = countMap.get("java");
if (count == null) {
countMap.put("java", 1);
} else {
countMap.put("java", count + 1);
}</code>JDK 8’s
getOrDefaultsimplifies the update, and
mergereduces it to one line.
<code>countMap.merge("java", 1, Integer::sum);</code>The
mergemethod calls the supplied remapping function only when the key already exists, otherwise it inserts the given value.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.