Java 25 (LTS) reference · Map and HashMap Methods

Java Map getOrDefault() Method

Return the value for a key, or a default value if the key isn't present. Avoids null checks.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.getOrDefault(key, defaultValue)

Parameters

ParameterDescription
key
Object
The key.
defaultValue
V
Returned when the key is missing.

Return value

The value or the default.

Examples

Default for missing keys
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = Map.of("mug", 12);
        System.out.println(stock.getOrDefault("mug", 0));
        System.out.println(stock.getOrDefault("kettle", 0));
    }
}

Output

12
0

Run this on your computer — see “Get Started” for setup.

Counting with a default
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> counts = new TreeMap<>();
        for (char c : "banana".toCharArray()) counts.put(c, counts.getOrDefault(c, 0) + 1);
        System.out.println(counts);
    }
}

Output

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

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?