Java中的属性 computeIfAbsent(Key, 函数 ) 方法及示例
Properties 类的computeIfAbsent(Key, 函数)方法允许您计算指定键的映射值,如果键尚未与值关联(或映射为 null)。
- 如果该方法的映射函数返回null,则不记录映射。
- 如果重映射函数抛出异常,则重新抛出异常,并记录无映射。
- 在计算过程中,不允许使用此方法修改此映射。
- 如果重映射函数在计算期间修改了此映射,则此方法将抛出 ConcurrentModificationException。
句法:
public Object computeIfAbsent?(Object key,
Function mappingFunction)
参数:此方法接受两个参数:
- key :与值关联的键。
- remappingFunction : 对值进行操作的函数。
返回:此方法返回与指定键关联的当前(现有或计算)值,如果映射返回 null ,则返回 null 。
异常:如果检测到重映射函数修改了此映射,则此方法抛出ConcurrentModificationException 。
下面的程序说明了 computeIfAbsent(Key, 函数) 方法:
方案一:
// Java program to demonstrate
// computeIfAbsent(Key, Function) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// Create a properties and add some values
Properties properties = new Properties();
properties.put("Pen", 10);
properties.put("Book", 500);
properties.put("Clothes", 400);
properties.put("Mobile", 5000);
// print Properties details
System.out.println("Current Properties: "
+ properties.toString());
// provide value for new key which is absent
// using computeIfAbsent method
properties.computeIfAbsent("newPen", k -> 600);
properties.computeIfAbsent("newBook", k -> 800);
// print new mapping
System.out.println("New Properties: "
+ properties.toString());
}
}
输出:
Current Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
New Properties: {newPen=600, Book=500, newBook=800, Mobile=5000, Pen=10, Clothes=400}
方案二:
// Java program to demonstrate
// computeIfAbsent(Key, Function) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// Create a properties and add some values
Properties properties = new Properties();
properties.put(1, "100RS");
properties.put(2, "500RS");
properties.put(3, "1000RS");
// print Properties details
System.out.println("Current Properties: "
+ properties.toString());
// provide value for new key which is absent
// using computeIfAbsent method
properties.computeIfAbsent(4, k -> "600RS");
// this will not effect anything
// because key 1 is present
properties.computeIfAbsent(1, k -> "800RS");
// print new mapping
System.out.println("New Properties: "
+ properties.toString());
}
}
输出:
Current Properties: {3=1000RS, 2=500RS, 1=100RS}
New Properties: {4=600RS, 3=1000RS, 2=500RS, 1=100RS}
参考资料:https://docs.oracle.com/javase/9/docs/api/ Java/util/Properties.html#computeIfAbsent-java.lang.Object-java.util。函数。函数-