Java HashMap getOrDefault() Method
Last Updated :
07 Apr, 2025
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.
What is getOrDefault() in HashMap?
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
Java
// Java Program to demonstrate the working of
// getOrDefault() with an exisiting key
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
// Create a HashMap and add key-value pairs
Map<String, Integer> hm = new HashMap<>();
hm.put("Geek1", 1);
hm.put("Geek2", 2);
// Key "Geek1" exists, so its
// associated value is returned
int a = hm.getOrDefault("Geek1", 0);
System.out.println("Value for 'Geek1': " + a);
}
}
OutputValue for 'Geek1': 1
Explanation: Geek1 exists in the map, so its associated value is returned.
Syntax of getOrDefault() Method
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:
- key: The key whose associated value is to be returned.
- defaultValue: The value to return if the specified key is not present in the map.
Example 2: Returning a Default Value when the Key does not exists
Java
// Java Program to demonstrate the working of
// getOrDefault() with an non-exisiting key
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
Map<String, Integer> hm = new HashMap<>();
hm.put("Geek1", 1);
hm.put("Geek2", 2);
// Key "Geek5" does not exists so
// the default value is returned
int a = hm.getOrDefault("Geek5", 0);
System.out.println("Value for 'Geek5': " + a);
}
}
OutputValue 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
Java
// Java Program to demonstrate how to handle cases
// where the key exists with null value or does not exist
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
Map<String, String> hm = new HashMap<>();
hm.put("Geek", null);
// Key "Geek" exists but its value is null,
// so null is returned
String s1 = hm.getOrDefault("Geek", "default");
System.out.println("Value for 'Geek': " + s1);
// Key "Geek2" does not exist, so
// the default value is returned
String s2 = hm.getOrDefault("Geek2", "default");
System.out.println("Value for 'Geek2': " + s2);
}
}
OutputValue 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.
How is it better that containsKey() and get()
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”);
Real-World Use Case
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:
- The getOrDefault() method is a simple and concise way to handle missing keys in a HashMap.
- If the key exists but it maps to null, we will still get null.
Similar Reads
HashMap get() Method in Java
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: Hash_Map.get(Object key_element)Parameter: The method takes one parameter key_e
2 min read
IdentityHashMap get() Method in Java
The java.util.IdentityHashMap.get() method of IdentityHashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: IdentityHashMap.get(Object key_element) Parameter: The method t
2 min read
Java HashMap computeIfAbsent() Method
In Java, the computeIfAbsent() method of the HashMap class is used to compute and insert a value for a specific key to a HashMap only if the key does not already have a value. Example 1: Here, the computeIfAbsent() adds a value for a key if it is not present in the map and does nothing if the key is
3 min read
Java HashMap computeIfPresent() Method
In Java, the computeIfPresent() method of the HashMap class is used to compute a new value for a specified key if the key is already present in the map and its value is not null. If the key is not present, no action is taken. Example 1: In this example, the computeIfPresent() method updates the valu
3 min read
Java HashMap containsValue() Method
In Java, the containsValue() method of the HashMap class is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. Example 1: This example demonstrates how the containsValue() method works when String values are mapped to integer keys. [GFGTABS] Jav
2 min read
Hashtable get() Method in Java
The java.util.Hashtable.get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key. Syntax: Hash_Table.get(Object key_element) Parameter: The method takes one parame
2 min read
Java HashMap put() Method
The put() method of the Java HashMap class is used to add or update the key-value pairs in the map. If the key already exists in the map, the previous value associated with the key is replaced by the new value and If the key does not exist, the new key-value pair is added to the map. Syntax of HashM
2 min read
ConcurrentHashMap get() Method in Java
The get() method in Java's ConcurrentHashMap class is used to retrieve the value associated with a given key. It has the following signature: V get(Object key) where: key is the key whose associated value is to be retrieved.The get() method works in a concurrent environment, which means that it can
3 min read
Java HashMap size() Method
The size() method of the Java HashMap class is used to retrieve the number of key-value pairs currently stored in the HashMap. Example 1: This example demonstrates the use of the size() method to get the number of elements in the HashMap. [GFGTABS] Java // Java program to demonstrates the working of
2 min read
IdentityHashMap put() Method in Java
The java.util.IdentityHashMap.put() method of IdentityHashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping, into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is pass
3 min read