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.
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)
}
}- 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?