Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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().

~4 min readJava
#Java#Map#HashMap#Null Handling
A Java Map diagram showing key-value pairs with a magnifying glass highlighting a value retrieval operation.

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.

java
Map<String, String> map = new HashMap<>(); map.put("key", null); String value = map.get("key"); // returns null, but the key exists

If 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.

java
Map<String, Integer> scores = new HashMap<>(); Integer score = scores.getOrDefault("player", 0); // returns 0 if key absent

A 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.

java
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:

  • HashMap allows one null key and any number of null values.
  • TreeMap does not allow null keys because entries are ordered, but it allows null values.
  • Hashtable and ConcurrentHashMap do not allow null keys or null values.

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.

  • HashMap offers average O(1) lookup based on hash codes.
  • TreeMap stores entries in sorted order and offers O(log n) lookup, which also supports range queries.
  • LinkedHashMap maintains insertion order by default and has retrieval performance similar to HashMap, 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:

java
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 tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.