The putIfAbsent
method in the Map
interface is a convenient way to insert a key-value pair into a map only if the key is not already associated with a value or is associated with null
. This avoids overwriting existing values.
map.putIfAbsent(key, value)
- Parameters:
key
: the key for the value to be inserted.value
: the value to associate with the key if no value is currently associated.- Returns:
- The current value associated with the key if it exists.
null
if no value was associated and the new key-value pair was successfully inserted.
Example Usage
import java.util.HashMap;
import java.util.Map;
public class MapPutIfAbsentExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
// Adding a key-value pair
map.put("key1", "value1");
// Trying to add the same key with a different value
map.putIfAbsent("key1", "newValue1");
// Adding a new key
map.putIfAbsent("key2", "value2");
// Printing the map
System.out.println(map);
}
}
Output
{key1=value1, key2=value2}