Java map.get(key) - 如果键不存在,自动执行 put(key) 并返回? [英] Java map.get(key) - automatically do put(key) and return if key doesn't exist?

查看:45
本文介绍了Java map.get(key) - 如果键不存在,自动执行 put(key) 并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我厌倦了以下模式:

value = map.get(key);
if (value == null) {
    value = new Object();
    map.put(key, value);
}

当您使用嵌套映射来表示多维结构时,此示例仅涉及要编写的额外代码的表面.

This example only scratches the surface of the extra code to be written when you have nested maps to represent a multi-dimensional structure.

我确信某处存在可以避免这种情况的方法,但我在谷歌上的努力没有产生任何相关的结果.有什么建议吗?

推荐答案

java.util.concurrent.ConcurrentMap 

来自 Java 8

Java.util.Map

putIfAbsent(K key, V value) 

返回映射到键的值,或者插入给定的值,如果没有映射到键的值,则插入 null.

which returns the value mapped to key or inserts the given value and null if no value is mapped for the key.

如果您需要对值进行惰性评估,则可以使用

If you need lazy evaluation of the value there is

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

这篇关于Java map.get(key) - 如果键不存在,自动执行 put(key) 并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆