Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 04 / Topic 7 of 10

HashMap<K, V>: a ready-made key → value lookup

A map stores key → value pairs and looks a value up by its key directly, instead of scanning a list for it. HashMap<K, V> is Java's ready-made, general-purpose map. Think of a store's price list on a clipboard: you look up "Milk" and read off the price, you don't scan every item on the shelf.

import java.util.HashMap;

class HashMapBasics {
    public static void main(String[] args) {
        HashMap<String, Integer> priceList = new HashMap<>();
        priceList.put("Rice", 1200);
        priceList.put("Dal", 450);
        priceList.put("Milk", 60);

        System.out.println(priceList.get("Dal"));
        System.out.println(priceList.get("Sugar"));            // not present -> null
        System.out.println(priceList.getOrDefault("Sugar", 0)); // a safe default instead

        System.out.println(priceList.containsKey("Milk"));
        priceList.put("Milk", 65); // same key again: replaces the old value
        System.out.println(priceList.get("Milk"));

        System.out.println("Size: " + priceList.size());

        System.out.println("--- keys ---");
        for (String item : priceList.keySet()) {
            System.out.println(item);
        }

        System.out.println("--- entries ---");
        for (var entry : priceList.entrySet()) {
            System.out.println(entry.getKey() + " -> ₹" + entry.getValue());
        }

        priceList.remove("Dal");
        System.out.println(priceList.containsKey("Dal"));
    }
}

Output, exactly as run (examples/05_hash_map_basics.java):

450
null
0
true
65
Size: 3
--- keys ---
Dal
Rice
Milk
--- entries ---
Dal -> ₹450
Rice -> ₹1200
Milk -> ₹65
false

Walk through what each call did:

  • get("Sugar") returns null for a missing key — Integer can be null (section 6), so this compiles, but using that null as an int would crash exactly like the unboxing crash above.
  • getOrDefault("Sugar", 0) is the safe version: "give me the value, or this fallback if the key isn't there."
  • put("Milk", 65) with a key that already exists replaces the old value (60 → 65); it does not create a second "Milk" entry.
  • keySet() gives you the keys to loop over; entrySet() gives you both the key and the value together, via entry.getKey() / entry.getValue(), which avoids calling get(key) again inside the loop.

⚠️ HashMap iteration order is not guaranteed. The keySet()/entrySet() loops above printed Dal, Rice, Milk — not insertion order (Rice, Dal, Milk), and not alphabetical order either. Running this exact program again on this exact machine and JDK gives the same order every time, because the order comes from each key's hash code and the map's current internal size, both of which are fixed here — but the Java language makes no promise about what that order is, and a different JDK version, a different number of entries, or removing and re-adding keys can change it. Never write code whose correctness depends on HashMap order. If you need keys in a specific order (insertion order, sorted order), that is a different, more specialized map — out of scope here, covered with the rest of the Collections Framework in Stage 2 Part 9.

Full program: examples/05_hash_map_basics.java.

Done here? The practice set for Part 4 — including the solutions — is on the part page.

Search the guide