Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.getOrDefault: look up a value with a fallback

Look up a key in a map. The fallback is returned only if there is no entry for the key, not if the key is explicitly mapped to `null`.

Version: Java SE 21

Syntax

java.util.Map<K, V>: default V getOrDefault(Object key, V defaultValue)
Call: map.getOrDefault(key, defaultValue)

Map.getOrDefault is a default instance method of java.util.Map<K, V>, available since Java 8. Map.getOrDefault() is shorthand for the method name, not a zero-argument call. Call map.getOrDefault(key, defaultValue): the key parameter is declared as Object, and both the fallback and the result have type V.

If the map has an entry for the key, the method returns its stored value, even if that value is null, as allowed by HashMap. Only a missing entry triggers the fallback. The method does not insert or replace anything. Unlike get(key), which returns null for a missing key, this method lets you supply a fallback. Java evaluates the fallback expression before the call, even if its value is not used.

For Map<String, Long>, use 0L: Java boxes this long literal to Long. Assigning the result to a long unboxes it; if the result is null, unboxing throws NullPointerException. For Map<String, Integer>, you can use map.getOrDefault("TOTAL", 0).

Depending on the implementation, an unsuitable key type may cause ClassCastException, and a null key may cause NullPointerException if the map does not allow it. The default implementation guarantees neither synchronization nor atomicity; check the documentation for your particular map.

Examples

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Long> counts = new HashMap<>();
        counts.put("books", 7L);
        counts.put("pending", null);

        long books = counts.getOrDefault("books", 0L);
        long games = counts.getOrDefault("games", 0L);
        Long pending = counts.getOrDefault("pending", 0L);

        System.out.println(books);
        System.out.println(games);
        System.out.println(pending);
        System.out.println(counts.containsKey("games"));
    }
}

Result

7
0
null
false

`books` has the value `7`, and the missing `games` entry yields `0`. The `pending` result is `null`, so it is kept in a `Long` variable. The final `false` shows that the lookup did not insert `games`.

Related lessons

  • Java · Lesson 43 · Advanced · Version: 2
  • Java · Lesson 56 · Basic · Version: 2
  • Java · Lesson 39 · Intermediate · Version: 2

Sources