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()
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<Integer, String> numbers = new HashMap<>();
// insert entries to the HashMap
numbers.put(1, "Java");
numbers.put(2, "Python");
numbers.put(3, "JavaScript");
System.out.println("HashMap: " + numbers);
// mapping for the key is present in HashMap
String value1 = numbers.getOrDefault(1, "Not Found");
System.out.println("Value for key 1: " + value1);
// mapping for the key is not present in HashMap
String value2 = numbers.getOrDefault(4, "Not Found");
System.out.println("Value for key 4: " + value2);
}
}
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.