本文主要是介绍Map之computeIfAbsent,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Map之computeIfAbsent
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,然后返回新vif ((v = get(key)) == null) {V newValue;if ((newValue = mappingFunction.apply(key)) != null) {// 将新v存入mapput(key, newValue);// 返回新vreturn newValue;}}return v;
}
这篇关于Map之computeIfAbsent的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!