Modern Map methods: getOrDefault, merge, computeIfAbsent
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A map can do a whole "check, then change" routine in one call. The Java 8 methods getOrDefault, computeIfAbsent, computeIfPresent, compute, merge and replaceAll replace the old if (map.containsKey(...)) blocks. The code gets shorter, and there is no gap between the check and the change where a bug can hide.
What you will learn
- Read with a fallback using getOrDefault
- Create or update one entry with computeIfAbsent, computeIfPresent and compute
- Combine old and new values with merge, and remove an entry by returning null
- Change every value with replaceAll and guard a change with replace(key, old, new)
- Choose the right Map method for a job and avoid changing the map inside its lambda
Topics in this lesson
- getOrDefault: read with a fallback
- computeIfAbsent and computeIfPresent
- compute and merge: change a value
- replaceAll, replace and remove with a value
- Which method for which job?
Key points
getOrDefaultreads with a fallback and never changes the map.computeIfAbsentmakes a value only when needed;computeIfPresentchanges only an existing one;computealways runs.merge(k, v, f)storesvfor a new key, elsef(old, v); anullresult fromcomputeormergeremoves the entry.- Never change the same map inside the lambda; read, calculate, then
put.
Interview questions this lesson answers
- What is the difference between
getOrDefaultandcomputeIfAbsent? - What do
compute,computeIfAbsentandcomputeIfPresentdo? - What happens when the lambda of
computeormergereturnsnull? - When would you choose
mergeinstead ofcompute? - Why should the lambda of
computeIfAbsentnot change the same map? - Are these methods thread-safe?
- Write a one-line page-visit counter.
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.