HashMap in daily use
Handle missing keys, counters and grouping without a single null check.
Open this lesson in the learning hubKey points
getreturnsnullfor a missing key — it never throws.getOrDefaultis usually what you meant.containsKeyis the honest way to distinguish "absent" from "present but mapped to null".merge(key, 1, Integer::sum)is the counter idiom: inserts 1 the first time, adds afterwards.computeIfAbsent(k, k -> new ArrayList<>()).add(v)is the grouping idiom. No null check, no double lookup.putIfAbsentreturns the existing value if there was one, otherwisenull.- HashMap allows one
nullkey and manynullvalues. Concurrent maps allow neither.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 5);
stock.put("pear", 2);
System.out.println("get(apple) : " + stock.get("apple"));
System.out.println("get(kiwi) : " + stock.get("kiwi"));
System.out.println("getOrDefault(kiwi) : " + stock.getOrDefault("kiwi", 0));
System.out.println("containsKey(kiwi) : " + stock.containsKey("kiwi"));
System.out.println("putIfAbsent(pear) : " + stock.putIfAbsent("pear", 99));
stock.merge("apple", 3, Integer::sum);
stock.merge("kiwi", 3, Integer::sum);
System.out.println("after merges : apple=" + stock.get("apple") + " kiwi=" + stock.get("kiwi"));
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String w : List.of("ant", "bee", "asp", "bat")) {
byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
}
System.out.println("grouped : " + byLetter);
new TreeMap<>(stock).forEach((k, v) -> System.out.println(" " + k + " -> " + v));
}
}
merge and computeIfAbsent replace almost every null check you were about to write.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.