Java HashMap putIfAbsent() Method

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

Definition

In Java, putIfAbsent(key, value) stores value under key only when the key has no mapping or is mapped to null. An existing non-null value is never overwritten.

It returns the current value when one exists, and null when the new value was stored. That makes "add unless taken" a single call instead of a containsKey check followed by put.

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. putIfAbsent was added in Java 8 as a default method of Map; HashMap overrides it with a single lookup.

Syntax

Pass the key and the value to store if the key is free.

Java
Map<String, String> users = new HashMap<>();
String r1 = users.putIfAbsent("neo", "[email protected]");   // null: stored
String r2 = users.putIfAbsent("neo", "[email protected]");   // "[email protected]": kept
CallWhat it does
map.putIfAbsent(k, v)Stores v if k is missing or null.
map.putIfAbsent(k, v) == nulltrue when the value was stored (if v is not null).
map.computeIfAbsent(k, f)Creates the value only when needed.
map.put(k, v)Always overwrites.

The value argument is evaluated before the call, even when it is not stored. If building it is costly, use computeIfAbsent().

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V putIfAbsent(K key, V value)

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

Parameters

ParameterDescription
key (K)The key to fill. May be null.
value (V)The value to store if the key is free.

Return Value

Return ValueDescription
VThe existing non-null value; the map was not changed.
nullThe key was missing or mapped to null, and value was stored.

Compare with Similar Methods

Conditional inserts:

MethodHow it differs
put(k, v)Always stores, replacing any old value.
computeIfAbsent(k, f)Lazily computes the value; returns the current value.
replace(k, v)The opposite: only stores when the key exists.
getOrDefault(k, d)Reads with a fallback but never stores.

Java Examples

Example 1 — Register Usernames Without Overwriting

Two new users register, then someone tries to take an existing username.

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

public class HashMapPutIfAbsentDemo {
    public static void main(String[] args) {
        Map<String, String> users = new HashMap<>();
        String r1 = users.putIfAbsent("neo", "[email protected]");
        String r2 = users.putIfAbsent("trin", "[email protected]");
        String r3 = users.putIfAbsent("neo", "[email protected]");

        System.out.println("neo registered: " + (r1 == null));
        System.out.println("trin registered: " + (r2 == null));
        System.out.println("second neo rejected, kept " + r3);
        System.out.println(users.size() + " users, neo -> " + users.get("neo"));
    }
}

How It Works

  1. Free names. neo and trin are not taken yet, so both values are stored and each call returns null.
  2. Taken name. The third call finds neo already mapped and returns the existing address instead of storing the new one.
  3. Return value as a signal. Checking for null tells whether the registration succeeded, with no separate containsKey.
  4. No overwrite. The map still has two users, and neo keeps the first address.

Example 2 — A null Value Is Treated as Absent

One plan has a null quota, one has a real quota, and one is missing.

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

public class HashMapPutIfAbsentNull {
    public static void main(String[] args) {
        Map<String, Integer> quota = new HashMap<>();
        quota.put("free", null);
        quota.put("pro", 100);

        Integer a = quota.putIfAbsent("free", 10);
        Integer b = quota.putIfAbsent("pro", 999);
        Integer c = quota.putIfAbsent("team", 500);

        System.out.println("free: returned " + a + ", now " + quota.get("free"));
        System.out.println("pro: returned " + b + ", now " + quota.get("pro"));
        System.out.println("team: returned " + c + ", now " + quota.get("team"));
    }
}

How It Works

  1. null gets filled. "free" is a key, but its value is null, so putIfAbsent treats it as absent and stores 10.
  2. Real value kept. "pro" already has 100, so 999 is ignored and 100 is returned.
  3. Missing key added. "team" does not exist, so 500 is stored and the call returns null.
  4. Same return for two cases. Both "free" and "team" returned null, meaning "the new value was stored", even though one key existed before.

Example 3 — putIfAbsent Creates Values Even When Unused

Group pets by type twice and count how many lists get created each way.

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

public class HashMapPutIfAbsentEager {
    static int created = 0;

    static List<String> newList() {
        created++;
        return new ArrayList<>();
    }

    public static void main(String[] args) {
        String[] pets = {"cat:Tom", "dog:Rex", "cat:Kit", "cat:Mo"};

        Map<String, List<String>> eager = new HashMap<>();
        for (String p : pets) {
            String[] parts = p.split(":");
            eager.putIfAbsent(parts[0], newList());
            eager.get(parts[0]).add(parts[1]);
        }
        System.out.println("putIfAbsent: lists created = " + created + ", cats = " + eager.get("cat"));

        created = 0;
        Map<String, List<String>> lazy = new HashMap<>();
        for (String p : pets) {
            String[] parts = p.split(":");
            lazy.computeIfAbsent(parts[0], k -> newList()).add(parts[1]);
        }
        System.out.println("computeIfAbsent: lists created = " + created + ", cats = " + lazy.get("cat"));
    }
}

How It Works

  1. Argument built first. Java evaluates newList() before calling putIfAbsent, so a list is created for all four pets, even when the key already has one.
  2. Wasted lists. Only two of those four lists (one for cats, one for dogs) are stored; the other two are thrown away.
  3. Lazy alternative. computeIfAbsent calls the lambda only for a missing key, so exactly two lists are created.
  4. Same grouping. Both maps end with the cats Tom, Kit, and Mo in input order; only the amount of wasted work differs.

Frequently Asked Questions

The existing value if the key already has a non-null value; otherwise null, after storing the new value.
Yes. A key mapped to null is treated as absent, so the new value is stored.
putIfAbsent() takes a ready-made value, which is always evaluated. computeIfAbsent() takes a function that runs only when the key is missing, and returns the current value.
No. HashMap is not thread-safe. Use ConcurrentHashMap for atomic putIfAbsent across threads.
Java 8 added it to the Map interface.

Next: remove()

Delete a mapping by key, or by key and value.

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

14 people found this page helpful