SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 11 / 25

Middle

How do getOrDefault, putIfAbsent, computeIfAbsent and merge differ?

Short answer

The four methods differ in two ways: whether they write to the map and when the value is created.

You need to Use
Read, with a default for a missing key getOrDefault
Write a value you already have putIfAbsent
Create a value when the key is missing (multimap, cache) computeIfAbsent
Combine with the old value (counting, summing) merge

3 points to say:

  1. getOrDefault only reads, never writes.
  2. computeIfAbsent creates the value only when the key is missing.
  3. merge combines with the old value, great for counting.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.