computeIfAbsent
接受两个参数:
key
- 需要关联特定值的键
mappingFunction
- 计算一个值的函数 (这是 Function 类型的函数接口,它接受一个参数并返回一个结果)。
除了使用 computeIfAbsent
方法之外,没有其他必要指定这些参数的方法。以下是使用此 Map
方法的示例:
输入:Map<String,Integer> map:{four = 4,one = 1,two = 2,three = 3,five = 5}
map.computeIfAbsent("ten", k -> new Integer(10)); // adds the new record to the map
map.computeIfAbsent("twelve", k -> null); // record is not added, the function returns a null
map.computeIfAbsent("one", k -> new Integer(999999)); // record is not updated, the key "one" already exists -
// and has a non-null value
map.put("eleven", null); // new record with null value
map.computeIfAbsent("eleven", k -> new Integer(11)); // updates the record with new value
输出结果:{four=4, one=1, eleven=11, ten=10, two=2, three=3, five=5}
考虑以下代码:map.computeIfAbsent("ten", k -> new Integer(10));
这段代码表示我想要向map
中插入一个新的映射(键值对)。方法computeIfAbsent
需要指定键,即"ten"。值是由Function
生成的,该函数以键作为输入参数并产生结果;结果被设置为映射的值。
在这个例子中,键值对被添加到了map中:"ten",10。
lambda表达式k -> new Integer(10)
是Function<String,Integer>
的实例。这段代码也可以表示为:
Function<String, Integer> fn = k -> new Integer(10);
map.computeIfAbsent("ten", fn);