Java HashMap computeIfAbsent() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, computeIfAbsent(key, mappingFunction) looks up key. If the key already has a non-null value, that value is returned and the function is not called. Otherwise the function computes a value from the key, which is stored and returned.

Because it returns the value that is now in the map, it is ideal for "get or create": map.computeIfAbsent(k, x -> new ArrayList<>()).add(item) groups items into lists in one line.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. computeIfAbsent was added in Java 8 as a default method of Map; HashMap overrides it.

Syntax

Pass the key and a function that creates the value from the key.

Java
Map<Character, List<String>> byLetter = new HashMap<>();
byLetter.computeIfAbsent('a', k -> new ArrayList<>()).add("apple");
byLetter.computeIfAbsent('a', k -> new ArrayList<>()).add("avocado");
// {a=[apple, avocado]}
CallWhat it does
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v)Group values under a key.
map.computeIfAbsent(n, x -> slow(x))Cache a costly result.
map.putIfAbsent(k, v)Eager version: v is built even if unused.

If the function returns null, nothing is stored and the method returns null. It never removes an existing mapping.

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V computeIfAbsent(K key,
        Function<? super K, ? extends V> mappingFunction)

// Default method in Map<K, V>, overridden by HashMap

Parameters

ParameterDescription
key (K)The key to look up or fill.
mappingFunction (Function<? super K, ? extends V>)Called with the key only when a value is needed. Must not be null.

Return Value

Return ValueDescription
VThe existing value, or the newly computed and stored value.
nullThe function returned null; nothing was stored.

Compare with Similar Methods

Filling missing keys:

MethodHow it differs
putIfAbsent(k, v)Takes a ready value; returns the old value or null.
compute(k, f)Always runs; can update and remove.
computeIfPresent(k, f)The opposite case: only existing keys.

Java Examples

Example 1 — Group Words by First Letter

Build a Map<Character, List<String>> without checking whether each list exists.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapComputeIfAbsentGroup {
    public static void main(String[] args) {
        String[] words = {"apple", "bean", "avocado", "cherry", "banana", "corn"};
        Map<Character, List<String>> byLetter = new HashMap<>();

        for (String w : words) {
            byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
        }
        System.out.println(byLetter);
        System.out.println("b words: " + byLetter.get('b').size());
    }
}

How It Works

  1. Character keys. w.charAt(0) returns a char, which is autoboxed to a Character key.
  2. Create once. The first word for each letter finds no list, so the lambda creates an empty ArrayList and stores it.
  3. Add to the returned list. computeIfAbsent returns the list now in the map, new or existing, so .add(w) always lands in the right group.
  4. Letter order here. A Character hashes to its own code, so a, b, and c fill neighboring buckets and print alphabetically, by luck.

Example 2 — Cache Slow Lookups

Load each price only once; repeated requests are answered from the map.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapComputeIfAbsentCache {
    static int loads = 0;

    static Integer loadPrice(String item) {
        loads++;
        return item.length() * 10;
    }

    public static void main(String[] args) {
        Map<String, Integer> cache = new HashMap<>();
        String[] requests = {"tea", "cake", "tea", "tea", "cake", "soup"};

        for (String r : requests) {
            int price = cache.computeIfAbsent(r, HashMapComputeIfAbsentCache::loadPrice);
            System.out.println(r + " -> " + price + " (loads: " + loads + ")");
        }
        System.out.println(requests.length + " requests, " + loads + " loads");
    }
}

How It Works

  1. Method reference. HashMapComputeIfAbsentCache::loadPrice acts as a Function<String, Integer>: a fake slow lookup that counts its calls.
  2. Miss, then hit. The first "tea" is not cached, so loadPrice runs; the next two "tea" requests return the stored 30 without calling it.
  3. Price rule. The fake price is the name length times 10: tea is 30, and cake and soup are both 40.
  4. Savings. Six requests needed only three loads, one per distinct item.

Example 3 — null Values Get Filled; null Results Store Nothing

A key mapped to null, a key with a value, and a function that returns null.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapComputeIfAbsentNull {
    public static void main(String[] args) {
        Map<String, String> nick = new HashMap<>();
        nick.put("Robert", null);
        nick.put("Catherine", "Cat");

        String a = nick.computeIfAbsent("Robert", k -> "Bob");
        String b = nick.computeIfAbsent("Catherine", k -> "Kate");
        String c = nick.computeIfAbsent("Xavier", k -> null);

        System.out.println("Robert -> " + a);
        System.out.println("Catherine -> " + b);
        System.out.println("Xavier -> " + c + ", stored? " + nick.containsKey("Xavier"));
        System.out.println("size " + nick.size());
    }
}

How It Works

  1. null counts as absent. Robert is a key, but his value is null, so the function runs and "Bob" replaces the null.
  2. Existing value wins. Catherine already has "Cat", so the "Kate" lambda is never called and "Cat" is returned.
  3. null result. For Xavier the function returns null, so no mapping is created and the method returns null.
  4. Size check. Only Robert and Catherine are keys, so the size stays at 2.

Frequently Asked Questions

The value now associated with the key: the existing value if there was one, otherwise the newly computed value (or null if the function returned null).
Use map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). The list is created the first time a key is seen.
No, unless the key is mapped to null. An existing non-null value is returned without calling the function.
computeIfAbsent() creates the value lazily and returns the current value. putIfAbsent() needs the value up front and returns the previous value (or null).
Not on the same HashMap: the recursive calls modify the map during the outer call. Since Java 9 HashMap throws ConcurrentModificationException. Use get and put instead.

Next: computeIfPresent()

Update a value only when the key is present.

computeIfPresent() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful