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:
getOrDefaultonly reads, never writes.computeIfAbsentcreates the value only when the key is missing.mergecombines 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.