Java Map Values: Retrieval and Null Handling
Learn how to retrieve Java Map values safely, interpret null returns, and choose the right method: get(), getOrDefault(), containsKey(), or computeIfAbsent().

Java's java.util.Map interface stores key-value pairs, and retrieving a value is one of the most common operations. The core method is get(), but its behavior with missing keys and null values can be surprising. This article explains the main retrieval methods, how they handle null, and the tradeoffs among common Map implementations.
The Basics of get() and Its Return Type
The get() method returns the value associated with a key, or null if the key is not present. This contract creates a subtle ambiguity when the map can contain null values: a null return can mean either the key is missing or the key explicitly maps to null.
Map<String, String> map = new HashMap<>();
map.put("key", null);
String value = map.get("key"); // returns null, but the key existsIf your map can contain null values, call containsKey() when you need to distinguish these two cases. For example, map.containsKey("key") returns true even though map.get("key") returns null.
Handling Missing Keys with getOrDefault
To provide a fallback value when a key is missing, use getOrDefault(). It returns the value associated with the key if present, or the supplied default otherwise.
Map<String, Integer> scores = new HashMap<>();
Integer score = scores.getOrDefault("player", 0); // returns 0 if key absentA common misunderstanding is that getOrDefault() treats a key mapped to null as missing. It does not. If the key is present with a null value, getOrDefault() returns null, not the default. Use this method when a missing key should produce the default value, and when your map does not store null values.
Conditional Retrieval and Insertion with computeIfAbsent
computeIfAbsent() retrieves a value if the key is present, or computes and inserts a value for an absent key. The mapping function is invoked only when the key is not already associated with a non-null value. This method is useful for caches and memoization, because it avoids repeated expensive computations in those patterns.
Map<String, List<String>> cache = new HashMap<>();
List<String> list = cache.computeIfAbsent("users", k -> new ArrayList<>());If a key is present but mapped to null, computeIfAbsent() treats it as absent and attempts to compute a new value. That makes it a safer choice than get() followed by an insertion check when null values are possible.
Null Values and Null Keys in Map Implementations
Null handling depends on the Map implementation:
HashMapallows onenullkey and any number ofnullvalues.TreeMapdoes not allownullkeys because entries are ordered, but it allowsnullvalues.HashtableandConcurrentHashMapdo not allownullkeys ornullvalues.
When a map can contain null values, get() alone cannot tell you whether a key exists. Use containsKey() or computeIfAbsent() to avoid ambiguity. For maps that forbid null values, such as ConcurrentHashMap, a null return from get() always means the key is absent.
Performance: HashMap vs TreeMap vs LinkedHashMap
The implementation affects retrieval performance.
HashMapoffers average O(1) lookup based on hash codes.TreeMapstores entries in sorted order and offers O(log n) lookup, which also supports range queries.LinkedHashMapmaintains insertion order by default and has retrieval performance similar toHashMap, with a little extra overhead for the linked list.
For most use cases, HashMap is the default choice. Use TreeMap when you need sorted iteration or range operations. Use LinkedHashMap when you need predictable iteration order without sorting.
The quality of key hash codes also matters. Poor hash distributions can degrade HashMap to O(n) in the worst case. In Java 8 and later, HashMap uses balanced trees for bins with many collisions, which limits that risk. If performance is critical, prefer immutable keys with well-distributed hash codes.
Concurrency and Value Retrieval
HashMap is not thread-safe. If one thread modifies it structurally while another reads it, retrieval can produce inconsistent results. For concurrent access, use ConcurrentHashMap. Its get() method is thread-safe and provides weakly consistent iteration, but it does not permit null keys or null values.
ConcurrentHashMap.computeIfAbsent() is atomic, which makes it useful for thread-safe caches. The mapping function is applied at most once per key, so concurrent callers do not waste work computing duplicate values:
ConcurrentHashMap<String, ExpensiveObject> cache = new ConcurrentHashMap<>();
ExpensiveObject obj = cache.computeIfAbsent("key", k -> createExpensiveObject(k));Choosing the Right Retrieval Method
Match the method to the semantics you need:
- If you know the key exists,
get()is sufficient. - If a missing key should produce a default value, use
getOrDefault(). - If you want to compute and store a value on first access, use
computeIfAbsent(). - If null values are possible and you need to know whether the key exists, use
containsKey().
Avoid the pattern of calling get() and then checking for null before deciding whether to insert a value: it fails when the map legitimately contains null values. Use computeIfAbsent() or an explicit containsKey() check instead. This avoids bugs and makes the intent clearer.
Understanding the null policy of each Map implementation is essential when retrieving values. HashMap and LinkedHashMap allow nulls, TreeMap allows null values but not null keys, and Hashtable and ConcurrentHashMap forbid both. Matching the retrieval method to that policy keeps the code correct and readable.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.