Java HashMap getOrDefault() Method
Example
Output the value of an entry in a map, or "Unknown" if it does not exist:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities.getOrDefault("England", "Unknown"));
System.out.println(capitalCities.getOrDefault("Canada", "Unknown"));
}
}
Definition and Usage
The getOrDefault()
method returns the value of the entry in the map which has a specified key. If the entry does not exist then the value of the second parameter is returned.
Syntax
public V get(Object key, V def)
V
refers to the data type of the values of the map.
Parameter Values
Parameter | Description |
---|---|
key | Required. Specifies the key of the entry to get the value from. |
def | Required. Specifies the default value to return if an entry is not found. |
Technical Details
Returns: | The value of the entry with the specified key or the value of the def argument if an entry with that key does not exist. |
---|
Related Pages
❮ HashMap Methods