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.
Map<String, String> map = new HashMap();
map.put("public", "xxx");
// possible NPE
System.out.println(map.get("pay").toUpperCase());Using Objects.isNull or the ternary operator can reduce boilerplate, but JDK 8’s Map#getOrDefault does it in one line.
String value = map.getOrDefault("pay", "");
System.out.println(value.toUpperCase());For pre‑JDK 8 environments, Apache Commons‑Lang3 MapUtils.getString provides similar functionality.
String value = MapUtils.getString(map, "pay", "");Using computeIfAbsent
When a key should map to a collection, the classic approach requires explicit null checks.
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");
}JDK 8’s computeIfAbsent replaces this with a single statement.
map.computeIfAbsent("javaFramework", k -> new ArrayList<>()).add("Spring"); 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.
Map<String, Integer> countMap = new HashMap();
Integer count = countMap.get("java");
if (count == null) {
countMap.put("java", 1);
} else {
countMap.put("java", count + 1);
}JDK 8’s getOrDefault simplifies the update, and merge reduces it to one line. countMap.merge("java", 1, Integer::sum); The merge method calls the supplied remapping function only when the key already exists, otherwise it inserts the given value.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
