Java HashMap

A HashMap stores data as key-value pairs, letting you look things up by a name or id instead of by a numeric position. If an ArrayList is like a numbered list, a HashMap is like a dictionary where each word (key) maps to a definition (value).

Sometimes an index is not the natural way to find data. If you want to look up a person's phone number by their name, or a product's price by its code, you need to associate a key with a value. That is exactly what a HashMap does. It lives in java.util and is one of the most useful collections in Java because lookups are very fast.

Creating a HashMap and adding pairs

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> ages = new HashMap<>();
    ages.put("Alice", 30);
    ages.put("Bob", 25);
    ages.put("Carol", 28);

    System.out.println(ages.get("Bob"));      // 25
    System.out.println(ages.containsKey("Al")); // false
    System.out.println(ages.size());          // 3
  }
}

The two generic types <String, Integer> say the keys are Strings and the values are Integers. The put method adds or updates a pair, and get retrieves a value by its key. If you put a value using a key that already exists, the old value is replaced rather than duplicated.

MethodWhat it does
put(key, value)Adds a pair or replaces an existing key's value
get(key)Returns the value for a key, or null if absent
getOrDefault(key, fallback)Returns the value, or the fallback if key is missing
containsKey(key)Returns true if the key exists
remove(key)Removes the pair for that key
keySet()Returns all the keys
size()Returns the number of pairs

Looping through a HashMap

Because a HashMap holds pairs, there are a few ways to loop over it. You can loop over the keys with keySet, or over both keys and values together using entrySet, which gives you an Entry object for each pair.

Iterating over keys and values

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

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> stock = new HashMap<>();
    stock.put("Apples", 50);
    stock.put("Pears", 20);

    for (Map.Entry<String, Integer> pair : stock.entrySet()) {
      System.out.println(pair.getKey() + ": " + pair.getValue());
    }
    // Apples: 50
    // Pears: 20 (order is not guaranteed)
  }
}
Note: A HashMap does not keep any particular order. If you print it or loop over it, the pairs may appear in a different order than you inserted them. If you need insertion order, use a LinkedHashMap instead; for sorted order, use a TreeMap.
Note: Calling get with a key that does not exist returns null, not an error. To avoid surprises, use getOrDefault to supply a fallback value, or check containsKey first.
  • HashMap stores key-value pairs for fast lookup by key.
  • Both keys and values are objects, so numbers use wrapper classes like Integer.
  • put adds or replaces, get retrieves, and containsKey checks existence.
  • Loop with entrySet to visit keys and values together; order is not guaranteed.

Exercise: Java HashMap

What ordering guarantee does a plain HashMap provide for its keys?