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()
: Theget()
method returns the value associated with the specified key if it exists. If the key is not present, it returnsnull
.-
getOrDefault()
: ThegetOrDefault()
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 ofnull
. -
Usage:
get()
: Useget()
when you are okay with receivingnull
if the key is not found, but be cautious with potentialNullPointerException
if you try to use the result without checking fornull
.getOrDefault()
: UsegetOrDefault()
when you want to avoid handlingnull
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("Orange"); // Key not present, returns null
System.out.println("Value using get(): " + value1); // Output: null
// Using getOrDefault() method
Integer value2 = map.getOrDefault("Orange", 0); // Key not present, returns default value 0
System.out.println("Value using getOrDefault(): " + value2); // Output: 0
}
}
Follow-up Questions
- When would you prefer using
getOrDefault()
overget()
? -
Answer: When you want to avoid
null
and provide a fallback value in case the key is missing. -
What happens if you use
get()
on a key that’s not in the map and then directly use the result? - Answer: You may encounter a
NullPointerException
if you attempt to use the result without checking fornull
.