Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
keyKThe key.
valueVThe 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 guest

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.