What is the difference between the get() method and getOrDefault() method in HashMap?

In Java's HashMap, both the get() and getOrDefault() methods are used to retrieve values associated with a key, but they have different behaviors when the key is not found in the map.

Key Differences

  • Behavior when Key is Absent:
  • get(): The get() method returns the value associated with the specified key if it exists. If the key is not present, it returns null.
  • getOrDefault(): The getOrDefault() method returns the value associated with the specified key if it exists. If the key is not present, it returns a specified default value instead of null.

  • Usage:

  • get(): Use get() when you are okay with receiving null if the key is not found, but be cautious with potential NullPointerException if you try to use the result without checking for null.
  • getOrDefault(): Use getOrDefault() when you want to avoid handling null values and prefer a fallback value when the key is not present in the map.

Example Usage

Here’s a simple example illustrating the difference between get() and getOrDefault():

import java.util.HashMap;
public class HashMapExample {  

public static void main(String args) {

HashMap<String, Integer> map = new HashMap<>();

map.put("Apple", 1);

map.put("Banana", 2);

// Using get() method
Integer value1 = map.get(&quot;Orange&quot;);  // Key not present, returns null
System.out.println(&quot;Value using get(): &quot; + value1);  // Output: null

// Using getOrDefault() method
Integer value2 = map.getOrDefault(&quot;Orange&quot;, 0);  // Key not present, returns default value 0
System.out.println(&quot;Value using getOrDefault(): &quot; + value2);  // Output: 0

}


}  


Follow-up Questions

  1. When would you prefer using getOrDefault() over get()?
  2. Answer: When you want to avoid null and provide a fallback value in case the key is missing.

  3. What happens if you use get() on a key that’s not in the map and then directly use the result?

  4. Answer: You may encounter a NullPointerException if you attempt to use the result without checking for null.