Java Associate Keys with Values
A map gives each key at most one current value. Replacing the value for an existing key does not create a second independent record with that same key.
Understand the idea
Choose a key that represents the identity you intend to look up. HashMap does not promise an iteration order, LinkedHashMap can preserve encounter order, and TreeMap orders keys using natural ordering or a comparator. containsKey distinguishes a missing key from a present key mapped to null when the implementation permits null values. Avoid null values when a simpler contract is possible.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.Map;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> seats = new LinkedHashMap<>();
seats.put("Clay", 4);
seats.put("Wood", 7);
seats.put("Clay", 6);
System.out.println(seats.get("Clay"));
System.out.println(seats.getOrDefault("Metal", 0));
System.out.println(seats);
}
}
Expected output
6
0
{Clay=6, Wood=7}The second Clay assignment replaces four with six. getOrDefault supplies zero for a missing Metal key without inserting it. LinkedHashMap keeps this printed demonstration deterministic. A map of aggregate counts is not interchangeable with the original list of individual bookings, because aggregation discards detail.
Check the official Java documentation for detailed contracts and supported options.