Java 25 (LTS) reference · Map and HashMap Methods

Java Map putIfAbsent() Method

Add a key-value pair only if the key is missing (or mapped to null). Returns the existing value otherwise.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.putIfAbsent(key, value)

Parameters

ParameterDescription
key
K
The key.
value
V
Value to add if absent.

Return value

The existing value, or null if it was added.

Examples

Defaults that don't overwrite
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, String> prefs = new HashMap<>(Map.of("theme", "dark"));
        prefs.putIfAbsent("theme", "light");
        prefs.putIfAbsent("lang", "en");
        System.out.println(new TreeMap<>(prefs));
    }
}

Output

{lang=en, theme=dark}

Run this on your computer — see “Get Started” for setup.

Remember the first occurrence
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> first = new HashMap<>();
        for (String visitor : List.of("ana", "ben", "ana")) first.putIfAbsent(visitor, first.size() + 1);
        System.out.println(new TreeMap<>(first));
    }
}

Output

{ana=1, ben=2}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?