English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the mapping for the specified key is not found in the hash map, the Java HashMap getOrDefault() method will return the specified default value.
Otherwise, the method returns the value corresponding to the specified key.
The syntax of the getOrDefault() method is:
hashmap.get(Object key, V defaultValue)
key - To return its mappingValuekey
defaultValue - Returns the specified defaultValue if the mapping for the specified key is not found
Returns the value associated with the specified key
Returns the specified defaultValue if the mapping for the specified key is not found
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating HashMap HashMap<Integer, String> numbers = new HashMap<>(); //Inserting an entry into the HashMap numbers.put(1, "Java"); numbers.put(2, "Python"); numbers.put(3, "JavaScript"); System.out.println("HashMap: " + numbers); //The key mapping exists in the HashMap String value1 = numbers.getOrDefault(1, "Not Found"); System.out.println("Key"}1Value: " + value1); //The key mapping does not exist in the HashMap String value2 = numbers.getOrDefault(4, "Not Found"); System.out.println("Key"}4value: " + value2); } }
Output Result
HashMap: {1=Java, 2=Python, 3=JavaScript} key1value: Java key4value: Not Found
In the above example, we created a hash map named numbers. Note the expression
numbers.getOrDefault(1, "Not Found")
Here,
1 - to return the key mapping value
Not Found - If the key does not exist in the hash map, it will return the default value
Since the hashmap contains the key mapping1. Therefore, Java will return this value.
But, please note the following expression:
numbers.getOrDefault(4, "Not Found")
Here,
4 - to return the key mapping value
Not Found - Default value
Since the hash map does not contain the key4any map. Therefore, it will return the default value Not Found.
Note: We can useHashMap containsKey()Method to check if a specific key exists in the hash map.