Map.put()
Stores a value under a key, replacing the old one.
Available since: Java 1.2
Syntax
V put(K key, V value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | K | The key. |
| value | V | The value for this key. |
Return value
VThe previous value of the key, or `null` if the key was absent.
Examples
Adding and replacing:
void main() {
Map<String, Integer> stock = new HashMap<>();
IO.println(stock.put("apples", 10));
IO.println(stock.put("apples", 7));
IO.println(stock);
}Output:
null
10
{apples=7}Notes
Each key appears once: a second put() overwrites the value. If you do not want to overwrite use putIfAbsent(), and for accumulating (counters, sums) use merge(). putAll(otherMap) copies all pairs of another map.
See also
- Map.get() — Returns the value for a key, or `null`.
- Map.putIfAbsent() — Stores a value only if the key is not present yet.
- Map.merge() — Adds a value under a key or combines it with the existing one.
- HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.