Absent /??bs?nt , ?b?sent/ ab相反s存在ent…的
从map中获取key对应的value,如果value不存在就用提供的Function创建一个新的value,然后存入map,最后返回
Map<String, Set<Pet>> statistics = new HashMap<>();
Set<Pet> pets = statistics.get(threadName);
if (pets == null) {
pets = new HashSet<>();
}
// 根据threadName获取pets,如果pets==null,则创建一个HashSet,然后将新建的HashSet存入map,最后返回新建的HashSet
Map<String, Set<Pet>> statistics = new HashMap<>();
Set<Pet> pets = statistics.computeIfAbsent(threadName, k -> new HashSet<>());
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
// 如果v有值,则直接返回v,如果v不存在,就创建新的v,并将新的v存入map,然后返回新v
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
// 将新v存入map
put(key, newValue);
// 返回新v
return newValue;
}
}
return v;
}