WeCodeAcademy

Java HashMap

A HashMap stores key-value pairs, like a dictionary. Lookups by key are very fast.

ExampleJava
import java.util.HashMap;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> ages = new HashMap<>();
    ages.put("Ada", 36);
    ages.put("Sam", 22);
    ages.put("Ada", 37);               // same key: replaces the value
    System.out.println(ages.get("Ada"));
    System.out.println(ages.containsKey("Lee"));
    System.out.println(ages.size());

    TreeMap<String, Integer> sorted = new TreeMap<>(ages); // keys in order
    for (String name : sorted.keySet()) {
      System.out.println(name + " -> " + sorted.get(name));
    }
  }
}
Output
37
false
2
Ada -> 37
Sam -> 22

A HashMap does not promise any order. If you need keys sorted, use a TreeMap, as in the last lines above.

Quick check

What does map.put("Ada", 37) do if "Ada" is already a key?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.