skip to content

How do getOrDefault and putIfAbsent simplify common Map access patterns, and how do they differ?

level: juniorimportance: must knowfreq 68%

answer

  1. getOrDefault = fallback, no insert
  2. putIfAbsent = insert only if missing, returns previous
  3. null mapping: the two methods differ
  4. putIfAbsent evaluates its value arg eagerly
  5. expensive default -> computeIfAbsent instead

basics

~20 s

getOrDefault(key, fallback) returns the value if the key exists, otherwise the fallback, and inserts nothing. putIfAbsent(key, value) stores the value only if the key is missing or maps to null, and returns the previous value.

solid answer

~50 s

Both replace verbose null-checking boilerplate. `getOrDefault(k, d)` is a read: it returns the mapped value if a mapping exists, else `d`, and inserts nothing — handy for read-time defaults like counters you don't want to insert. `putIfAbsent(k, v)` is a conditional write: it inserts `v` only when `k` is absent or currently mapped to null, and returns the *previous* value (null if it inserted). A key subtlety on maps that permit null values: the two differ on a key explicitly mapped to null. getOrDefault returns that null, because the key has a mapping, while putIfAbsent treats it as absent and overwrites the null. Also, `putIfAbsent` always evaluates its `v` argument eagerly even when the key is present — if computing `v` is expensive or has side effects, prefer `computeIfAbsent`, which only invokes its mapping function on a miss.

go deeper

for a junior

Knows getOrDefault returns a fallback without inserting and putIfAbsent inserts only when missing.

for a middle

Explains the return values and the eager-vs-lazy difference between putIfAbsent and computeIfAbsent.

for a senior

Articulates how a null mapping splits the two methods and which implementations (HashMap vs ConcurrentHashMap) permit null.

for a principal

Chooses the right primitive for correctness and cost across single-threaded and concurrent maps, and reasons about side-effect timing.

### The problem these solve Before Java 8, reading a map with a fallback meant: `V v = map.get(k); if (v == null) v = fallback;`. And "insert only if missing" meant: `if (!map.containsKey(k)) map.put(k, v);`. These default methods on the `Map` interface fold that boilerplate into one call. ### getOrDefault(key, defaultValue) Returns the value mapped to `key` **if the key is present**, otherwise returns `defaultValue`. Crucially it **inserts nothing**: no entry is created. (On an access-order `LinkedHashMap`, a hit still counts as an access and moves that entry.) Example, counting without polluting the map: ```java int count = counts.getOrDefault(word, 0); ``` This returns 0 for an unseen word but does **not** store `word -> 0`. ### putIfAbsent(key, value) A **conditional write**. If `key` is absent (or currently mapped to `null`), it stores `value` and returns `null`. If `key` already has a non-null value, it **does nothing** and returns the **existing** value. So the return value tells you what was there before: ```java Value prev = map.putIfAbsent(k, newValue); // prev == null means we inserted ``` ### The null subtlety (important) The two methods treat a key *explicitly mapped to null* differently, and the `Map` contract spells out both: - `getOrDefault(k, d)` returns **null**. The default is only for "no mapping for the key", and the default implementation checks `containsKey` before using it. On JDK 27, all four of `HashMap`, `LinkedHashMap`, `TreeMap` and an `AbstractMap` subclass return null. So this is where it parts ways with the hand-written `get`-then-check above, which would use the fallback. - `putIfAbsent(k, v)` treats the key as absent: it **overwrites** the null with `v` and returns null. This matters for maps that permit null values, such as `HashMap`. `ConcurrentHashMap` forbids null entirely, so the case cannot arise there. ### Eager argument evaluation `putIfAbsent(k, expensive())` always **computes `expensive()`** before the call, even if `k` is present and the value is thrown away — because Java evaluates arguments before invoking the method. If the value is costly to build, or building it should happen *only* on a miss, use `computeIfAbsent(k, key -> expensive())` instead, which is **lazy**: it runs the function only when the key is absent. ### When to use which - Need a fallback but don't want to insert: **getOrDefault**. - Want to insert a default and keep any existing value: **putIfAbsent**. - Insertion default is expensive or you need the key to build it: **computeIfAbsent**.

  • Does getOrDefault(k, 0) add k->0 to the map?
    No. getOrDefault returns the default and inserts nothing.
  • Why might putIfAbsent be wrong when the default is costly to build?
    Its value argument is evaluated eagerly every call, even on a hit; computeIfAbsent runs its mapping function only on a miss, so it avoids the wasted work.
  • What does getOrDefault return for a key explicitly mapped to null?
    null. The default is only for a key with no mapping, so a HashMap holding k -> null returns null from getOrDefault(k, d). putIfAbsent(k, v) differs: it treats that key as absent and overwrites the null.

  • Saying getOrDefault inserts the default into the map
  • Thinking putIfAbsent returns the new value (it returns the previous)
  • Saying getOrDefault returns the default for a key explicitly mapped to null
  • Using putIfAbsent with an expensive value argument
  • Thinking putIfAbsent leaves an existing null mapping in place

Map.getOrDefault and Map.putIfAbsent
Java 1.8

Assumes JDK 27; both are Map default methods since Java 8, and their contract reads the same at JDK 25.

context