Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

Java Map.getOrDefault()

Reference for Map.getOrDefault(): return a fallback value when a key is missing, how it treats null values, and when it is not the right tool.

getOrDefault(key, defaultValue) looks up a key and returns its value, or the default you supply if the map has no mapping for that key. It replaces the old pattern of calling get(), checking for null, and choosing a fallback.

It does not store anything. The default is only returned; the map is not changed. If you want the default to be inserted as well, use computeIfAbsent() or putIfAbsent().

Java
int count = counts.getOrDefault(word, 0);

Try it

Java Defaults without null checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Null values are not 'missing'

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
default V getOrDefault(Object key, V defaultValue)
Name Description
key The key to look up.
defaultValue Value to return if there is no mapping for key. Can be null.

Returns: the mapped value, or defaultValue when the map has no mapping for the key. A key that is mapped to null counts as present, so null is returned for it.

Throws: ClassCastException or NullPointerException if the key is not acceptable to the map (for example null with a TreeMap or Map.of()).

Usage notes

  • Since Java 8. It is a default method of Map; HashMap, TreeMap and ConcurrentHashMap override it.
  • Does not modify the map. Use computeIfAbsent() to store a created value, or merge() for counters.
  • Eager default: the default argument is always evaluated. For expensive defaults use computeIfAbsent() (lazy) or an explicit containsKey check.
  • Null values: a key explicitly mapped to null returns null, not the default, in every standard map. Avoid null values if that distinction matters.
  • Counting idiom: m.put(k, m.getOrDefault(k, 0) + 1) works, but m.merge(k, 1, Integer::sum) does a single lookup and is atomic on ConcurrentHashMap.
  • Lists as defaults: getOrDefault(k, List.of()) is handy for read-only access, but adding to that default list does not update the map (and the immutable list would throw).
  • Immutable maps: Map.of(...).getOrDefault(null, x) throws NullPointerException.