Map.putIfAbsent()
Stores a value only if the key is not present yet.
Available since: Java 8
Syntax
default V putIfAbsent(K key, V value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | K | The key. |
| value | V | The value stored only if the key is absent. |
Return value
VThe current value of the key, or `null` if the pair was added.
Examples
An existing value is not overwritten:
void main() {
Map<String, String> users = new HashMap<>(Map.of("anna", "admin"));
users.putIfAbsent("anna", "guest");
users.putIfAbsent("oleg", "guest");
IO.println(users.get("anna") + " " + users.get("oleg"));
}Output:
admin guestNotes
The value is evaluated before the call, even if it is not needed. When creating the value is expensive (a new list, a database query), prefer computeIfAbsent() — it calls its function only when the key is absent.
See also
- Map.put() — Stores a value under a key, replacing the old one.
- Map.computeIfAbsent() — Returns the value for a key, creating it with a function if the key is absent.
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
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.