Java Map.put and Map.get
Store a value by key and retrieve it with get. Putting a value for an existing key replaces its previous mapping.
A simple example
Map.put and Map.get
- Start with A = 1
- Do this Store 2 at key A
- Result A = 2
Syntax
inventory.put(key, value)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaUpdate the count for a shelf label
A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.
import java.util.HashMap;
class Main {
public static void main(String[] args) throws Exception {
var stock = new HashMap<String, Integer>();
stock.put("Tea", 3);
stock.put("Tea", 7);
System.out.println(stock.get("Tea"));
}
}
7
Reusing the Tea key updates the existing entry, so the lookup returns seven.
Keep the old room assignment on a change slip
A tutor moves an evening class to another room. Reception needs both the previous room and its replacement so it can put a change slip on the old classroom door.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var rooms = new HashMap<>(Map.of("Evening", "A2"));
String old = rooms.put("Evening", "B1");
System.out.println(old + " -> " + rooms.get("Evening"));
}
}
A2 -> B1
put returns A2 while the new mapping makes subsequent lookups return B1.
Revise a locker assignment
A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
What to watch for
get can return null for a missing key or a mapped null when null values are permitted. Use containsKey when the distinction matters.