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
Syntax
map.putIfAbsent(key, value)
Parameters
| Parameter | Description |
|---|---|
keyK |
The key. |
valueV |
Value to add if absent. |
Return value
The existing value, or null if it was added.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
map.computeIfAbsent()· Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping.map.put()· Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null.- Java HashMap · tutorial