Library contents

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

  1. Start with A = 1
  2. Do this Store 2 at key A
  3. Result A = 2
Looking up the same key now returns the new value.

Syntax

Java syntax
inventory.put(key, value)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Update 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.

Result7
Main.java
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"));
    }
}
Output
7

Reusing the Tea key updates the existing entry, so the lookup returns seven.

Advertisements

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.

ResultA2 -> B1
Main.java
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"));
    }
}
Output
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?

Givengreen → 6, then green → 9
Worked result9

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.

Documentation for Map.put and Map.get