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
Syntax
map.getOrDefault(key, defaultValue)
Parameters
| Parameter | Description |
|---|---|
keyObject |
The key. |
defaultValueV |
Returned when the key is missing. |
Return value
The value or the default.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
map.get()· Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.map.merge()· Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values.- Java HashMap · tutorial