![]() |
VOOZH | about |
When we work with Java's HashMap, one common problem occurs that is dealing with missing keys. If we try to fetch a value for a key that does not exist, we get "null" and sometimes it may throw NullPointerException.
To solve this problem, Java provides a method called getOrDefault() of the HashMap class. In this article, we will learn about the working of the Java HashMap getOrDefault() method.
This method getOrDefault(Object key, V defaultValue) retrieves the value associated with a given key if it exists in the map. If the key does not exist, it returns a default value provided by the user. This is helpful when we work with maps that might not always contain every possible key.
Let's first see a basic example of getOrDefault() of HashMap.
Example 1:Retrieve the Value when the Key exists
Value for 'Geek1': 1
Explanation: Geek1 exists in the map, so its associated value is returned.
public V getOrDefault(Object key, V defaultValue)
V: It represents the type of the value that the map holds. It is a generic type and it will match the type of the values in the HashMap.
Parameters:
Example 2: Returning a Default Value when the Key does not exists
Value for 'Geek5': 0
Explanation: In the above example, it does not returns "null", it returns the default value 0.
Example 3: Key exists but the value is null
Value for 'Geek': null Value for 'Geek2': default
Explanation: In the above example, the getOrDefault() method returns null, because the key exists but its value is explicitly set to null.
The traditional way to fetch values is:
String value;
if (map.containsKey(key)) {
value = map.get(key);
} else {
value = "default";
}
The same thing can be done in one line with:
String value = map.getOrDefault(key, "default");
Suppose we are building a voting system that stores vote counts by candidate name,
Map<String, Integer> votes = new HashMap<>();
// If "Sweta" has not received any votes yet, return 0
int i = votes.getOrDefault("Sweta", 0);
votes.put("Sweta", i + 1);
Here, the getOrDefault() shows that the count starts at 0 even if the key is missing.
Important Points: