Advanced Java: Collections, Generics and More ยท The Collections Framework

HashMap: Look Up by Key

Store values under keys, replace them, read missing keys safely, and loop over every entry.

HashMapDemo.java

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("apple", 5);
        stock.put("pear", 2);
        stock.put("apple", 8);                 // same key: the value is replaced
        int apples = stock.get("apple");
        Integer kiwis = stock.get("kiwi");     // missing key: null
        boolean hasPear = stock.containsKey("pear");
        int total = 0;
        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            total += e.getValue();
        }
        System.out.println(apples + " " + kiwis + " " + hasPear + " " + total);
    }
}

Step by step

  1. An empty HashMap from String keys to Integer values.
  2. A new key apple with the value 5 is added to the HashMap that stock points to.
  3. A new key pear with the value 2 is added to the HashMap that stock points to.
  4. Same key again: the old value 5 is replaced by 8. Keys are unique.
  5. apples is created on the stack with the value 8.
  6. No "kiwi" key: get returns null.
  7. hasPear is created on the stack with the value true.
  8. total is created on the stack with the value 0.
  9. e is created on the stack and points to a new HashMap$Node on the heap: apple=8.
  10. entrySet gives each key-value pair in turn.
  11. The end of this block is reached.
  12. e is created on the stack and points to a new HashMap$Node on the heap: pear=2.
  13. total changes from 8 to 10. e goes out of scope and disappears.
  14. The end of this block is reached.
  15. Java moves to the next element of the loop: for (Map.Entry<String, Integer> e : stock.entrySet()).
  16. It prints 8 null true 10.
  17. 8, null, true and a total of 10 (8 + 2).