Java SE API
Map.getOrDefault
Read with an explicit fallback for a missing key, not for a present null.
Formal Syntax & Structure
java syntaxjava
default V getOrDefault(Object key, V defaultValue)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | Object | Lookup key. |
| defaultValue | V | Value used for an absent mapping. |
Return Value
V
Mapped value if present; otherwise the supplied default.
Working Example
Example Snippetjava
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, Integer> stock = new HashMap<>(); stock.put("pen", 4); stock.put("book", null); System.out.println(stock.put("pen", 7)); System.out.println(stock.get("pen")); System.out.println(stock.getOrDefault("ruler", 0)); System.out.println(stock.getOrDefault("book", 0)); System.out.println(stock.containsKey("book")); System.out.println(stock.containsKey("ruler")); }}