Java
HashMap
Default Value
Key-Value
Programming Tips

HashMap to return default value for non-found keys?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

In Java, a HashMap returns null when a key is missing, which is often inconvenient when you want a fallback value. The simplest fix is getOrDefault, but that method only changes what is returned. It does not insert anything into the map.

That detail matters because there are really three different needs people confuse with each other: read with a fallback, insert a missing value, or accumulate data for a key.

Use getOrDefault for Read-Time Fallbacks

If you only want a fallback when reading, use getOrDefault.

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class DefaultReadExample {
5    public static void main(String[] args) {
6        Map<String, Integer> counts = new HashMap<>();
7        counts.put("apple", 3);
8
9        System.out.println(counts.getOrDefault("apple", 0));
10        System.out.println(counts.getOrDefault("banana", 0));
11    }
12}

This is the cleanest replacement for old patterns such as:

java
Integer value = map.containsKey(key) ? map.get(key) : defaultValue;

Important Detail: It Does Not Modify the Map

A lot of bugs happen because developers assume getOrDefault writes the default into the map. It does not.

java
1Map<String, Integer> counts = new HashMap<>();
2int value = counts.getOrDefault("banana", 0);
3
4System.out.println(value);
5System.out.println(counts.containsKey("banana"));

The second line prints false because the map is still unchanged.

If you actually want the missing key to appear in the map, use putIfAbsent or computeIfAbsent instead.

Use computeIfAbsent When Missing Keys Should Be Created

computeIfAbsent is useful when the default is expensive to build or when the default is a mutable value such as a list or set.

java
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.List;
4import java.util.Map;
5
6public class ComputeExample {
7    public static void main(String[] args) {
8        Map<String, List<String>> groups = new HashMap<>();
9
10        groups.computeIfAbsent("admin", key -> new ArrayList<>()).add("alice");
11        groups.computeIfAbsent("admin", key -> new ArrayList<>()).add("bob");
12
13        System.out.println(groups);
14    }
15}

This both returns a value and stores it if it was missing.

Counting and Accumulation Patterns

For counters, getOrDefault is fine when you reinsert the updated value.

java
1Map<String, Integer> counts = new HashMap<>();
2String key = "apple";
3
4counts.put(key, counts.getOrDefault(key, 0) + 1);
5System.out.println(counts);

For some cases, merge is even cleaner:

java
counts.merge("apple", 1, Integer::sum);
counts.merge("apple", 1, Integer::sum);
System.out.println(counts);

This is often the best pattern for frequency maps.

Null Values Need Care

Another subtle point is that HashMap allows null values. That means a missing key and a present key with value null are not exactly the same concept.

getOrDefault returns the mapped value if the key is present, even if that value is null? Actually for Map.getOrDefault, if the key is mapped to null, the method returns null, not the default, because the key is present.

That is important if you are using null as a meaningful stored value.

Common Pitfalls

The biggest mistake is expecting getOrDefault to insert the default into the HashMap. It does not.

Another common issue is using getOrDefault when computeIfAbsent or merge better matches the actual goal.

People also forget that HashMap can store null values. A missing key and a key mapped to null are different cases.

Finally, avoid writing long manual containsKey branches unless you truly need custom logic. Modern Map methods are clearer and less error-prone.

Summary

  • Use getOrDefault when you only need a fallback at read time.
  • 'getOrDefault does not modify the map.'
  • Use computeIfAbsent when a missing key should create and store a value.
  • Use merge for concise counter-style updates.
  • Be careful with null because HashMap allows it as a stored value.
  • Pick the method that matches whether you want to read, create, or accumulate.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms