putIfAbsent
时间: 2023-10-13 09:19:48 浏览: 95
java8源码-example:常见的java知识点代码示例
putIfAbsent method is a method of the Map interface in Java. It is used to add an entry to the map only if the specified key is not already present in the map.
If the key is not present, the method adds the key-value pair to the map and returns null. If the key is already present, the method does not modify the map and returns the existing value associated with the key.
Syntax:
```
V putIfAbsent(K key, V value)
```
Parameters:
- key: the key to be added to the map
- value: the value associated with the key
Return Value:
- null if the key was not present in the map
- the existing value associated with the key if the key was already present in the map
Example:
```
Map<String, Integer> map = new HashMap<>();
Integer oldValue = map.putIfAbsent("key", 1);
if (oldValue == null) {
System.out.println("The key 'key' was not present in the map. Added with value 1.");
} else {
System.out.println("The key 'key' was already present in the map with value " + oldValue);
}
```
Output:
```
The key 'key' was not present in the map. Added with value 1.
```
阅读全文