Otherwise, the method returns the value corresponding to the specified key.
The syntax of the getOrDefault() method is:
hashmap.get(Object key, V defaultValue)
Here, hashmap is an object of the HashMap class.
getOrDefault() Parameters
The getDefault() method takes two parameters.
- key - key whose mapped value is to be returned
- defaultValue - value which is returned if the mapping for the specified key is not found
getOrDefault() Return Value
- returns the value to which the specified key is associated
- returns the specified defaultValue if the mapping for specified key is not found
Example: Java HashMap getOrDefault()
Output
HashMap: {1=Java, 2=Python, 3=JavaScript}
Value for key 1: Java
Value for key 4: Not Found
In the above example, we have created a hashmap named numbers. Notice the expression,
numbers.getOrDefault(1, "Not Found")
Here,
- 1 - key whose mapped value is to be returned
- Not Found - default value to be returned if the key is not present in the hashmap
Since the hashmap contains a mapping for key 1. Hence, the value Java is returned.
However, notice the expression,
numbers.getOrDefault(4, "Not Found")
Here,
- 4 - key whose mapped value is to be returned
- Not Found - default value
Since the hashmap does not contain any mapping for key 4. Hence, the default value Not Found is returned.
Note: We can use the HashMap containsKey() method to check if a particular key is present in the hashmap.