HashMap in daily use

Collections · lesson 6 of 42 · 3 min read

Handle missing keys, counters and grouping without a single null check.

Open this lesson in the learning hub

Key points

  • get returns null for a missing key — it never throws. getOrDefault is usually what you meant.
  • containsKey is 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.
  • putIfAbsent returns the existing value if there was one, otherwise null.
  • HashMap allows one null key and many null values. 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.