Video in progress
How do Map's getOrDefault, putIfAbsent and merge simplify your code?
They fold the "is the key there or not" check into a single call. getOrDefault returns a fallback for a missing key, putIfAbsent writes only into an empty slot, and merge combines the old and new value.
📖 Answer
Counting words is the classic example. The old style:
Map<String, Integer> count = new HashMap<>();
for (String w : words) {
if (count.containsKey(w)) {
count.put(w, count.get(w) + 1);
} else {
count.put(w, 1);
}
}
Since Java 8:
for (String w : words) {
count.merge(w, 1, Integer::sum);
}
Other useful methods:
count.getOrDefault("salom", 0): nonullcheck;cache.putIfAbsent(id, value): leaves it alone if it is already there;groups.computeIfAbsent(dept, k -> new ArrayList<>()).add(emp): very handy for grouping.
One subtle point: if the function passed to merge returns null, the key is removed from the map.
Sign up to mark studied questions and save your progress.