Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.getOrDefault()

Returns the value for a key, or a fallback when the key is absent.

Available since: Java 8

Syntax

default V getOrDefault(Object key, V defaultValue)

Parameters

ParameterTypeDescription
keyObjectThe key to look up.
defaultValueVWhat to return if the key is absent.

Return value

VThe key's value, or `defaultValue`.

Examples

Settings with default values:

void main() {
    Map<String, String> config = Map.of("theme", "dark");
    IO.println(config.getOrDefault("theme", "light"));
    IO.println(config.getOrDefault("lang", "en"));
}

Output:

dark
en

A character counter:

void main() {
    Map<Character, Integer> freq = new TreeMap<>();
    for (char c : "banana".toCharArray()) {
        freq.put(c, freq.getOrDefault(c, 0) + 1);
    }
    IO.println(freq);
}

Output:

{a=3, b=1, n=2}

Notes

The fallback value is not stored in the map. If it should be stored use putIfAbsent() or computeIfAbsent(). A counter is shorter with merge(key, 1, Integer::sum).

See also

  • Map.get() — Returns the value for a key, or `null`.
  • Map.merge() — Adds a value under a key or combines it with the existing one.
  • Map.computeIfAbsent() — Returns the value for a key, creating it with a function if the key is absent.

Related recipes

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.