Java 8 Map API Enhancements
Java 8 enriches the Map interface with default methods such as getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent and replace, allowing developers to retrieve values with fallbacks, iterate entries, combine or conditionally update entries, and thus write more concise, readable code with far less boilerplate.
Java's Map interface received several useful default methods in JDK 8 that simplify common operations such as retrieving a value with a fallback, iterating entries, merging, and conditional updates.
getOrDefault returns the value associated with a key or a supplied default when the key is absent. Example:
private static void testGetOrDefault() {
Map
map = new HashMap<>(4);
map.put("123", "123");
String key = "key";
String defaultValue = "defaultValue";
// old way
String oldValue = defaultValue;
if (map.containsKey(key)) {
oldValue = map.get(key);
}
System.out.println("oldValue = " + oldValue);
// new way
String newValue = map.getOrDefault(key, defaultValue);
System.out.println("newValue = " + newValue);
}forEach allows a lambda expression to process each entry without explicit iteration:
private static void testForeach() {
Map
map = new HashMap<>(4);
map.put("123", "123");
// old way
for (Map.Entry
entry : map.entrySet()) {
System.out.printf("old key = %s, value = %s%n", entry.getKey(), entry.getValue());
}
// new way
map.forEach((key, value) -> System.out.printf("new key = %s, value = %s%n", key, value));
}merge combines an existing value with a new one using a remapping function. A typical use is counting occurrences in a list:
private static void testMerge() {
Map
cntMap = new HashMap<>(8);
List
list = Arrays.asList("apple", "orange", "banana", "orange");
// old way
for (String item : list) {
if (cntMap.containsKey(item)) {
cntMap.put(item, cntMap.get(item) + 1);
} else {
cntMap.put(item, 1);
}
}
// new way
for (String item : list) {
cntMap.merge(item, 1, Integer::sum);
}
}putIfAbsent inserts a key‑value pair only when the key is not already present:
private static void testPutIfAbsent() {
Map
scoreMap = new HashMap<>(4);
scoreMap.put("Jim", 88);
scoreMap.put("Lily", 90);
// old way
if (!scoreMap.containsKey("Lily")) {
scoreMap.put("Lily", 98);
}
// new way
scoreMap.putIfAbsent("Lily", 98);
}compute lets you recompute a value based on its current state. The example below updates a frequency map:
private static void testComputer() {
Map
cntMap = new HashMap<>(8);
List
list = Arrays.asList("apple", "orange", "banana", "orange");
// old way
for (String item : list) {
if (cntMap.containsKey(item)) {
cntMap.put(item, cntMap.get(item) + 1);
} else {
cntMap.put(item, 1);
}
}
// new way
for (String item : list) {
cntMap.compute(item, (k, v) -> (v == null) ? 1 : v + 1);
}
}computeIfAbsent computes a value only when the key is missing, which is handy for recursive structures such as memoizing Fibonacci numbers:
private static void testComputerIfAbsent() {
Map
fibMap = new ConcurrentHashMap<>(16);
fibMap.put(0, 1);
fibMap.put(1, 1);
System.out.println(fib(5, fibMap));
}
private static Integer fib(Integer index, Map
fibMap) {
return fibMap.computeIfAbsent(index, i -> fib(i - 2, fibMap) + fib(i - 1, fibMap));
}computeIfPresent runs the remapping function only when the key already exists, while replace updates a value conditionally.
Overall, these JDK 8 default methods enable more concise and expressive Map manipulation, reducing boilerplate and improving readability.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.