java.util.Map.getOrDefault(key, defaultValue)
The method Map.getOrDefault(key, defaultValue) returns mapped value for the given key or defaultValue if there is no such mapping.
Method signature
The signature of the java.util.Map.getOrDefault(key, defaultValue) method is as follows:
default V getOrDefault(Object key, V defaultValue)
The method is available since Java 8.
Parameters
- Object key: the key whose associated value is to be returned
- V defaultValue: the default mapping of the key
Return value
Returns the value for given key or defaultValue if there is no mapping for the given key.
Exceptions
- ClassCastException: if the key is of an inappropriate type for this map (optional)
- NullPointerException: if the specified key is null and this map does not permit null keys (optional)
Example usage
In the following code we use java.util.Map.getOrDefault(key, defaultValue) to simplify getting values from a map:
package com.farenda.java.util; import java.util.HashMap; import java.util.Map; public class MapExamples { public static void main(String[] args) { Map<Integer,String> vilians = new HashMap<>(); vilians.put(1, "Kajko"); System.out.println("Original map: " + vilians); // pre Java 8 version: String name; if (vilians.containsKey(2)) { name = vilians.get(2); } else { name = "Kokosz"; } System.out.println("Name: " + name); // Java 8 version: name = vilians.getOrDefault(2, "Kokosz"); System.out.println("Name: " + name); } }
The above code produces the following output:
Original map: {1=Kajko} Name: Kokosz Name: Kokosz