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

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

问题描述

我感到以下模式:

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

这个例子只是在你有嵌套的地图代表一个多维的结构。



我确定存在一些存在的东西来避免这种情况,但是我的Google搜索工作没有任何关联。任何建议?

解决方案

  java.util.concurrent.ConcurrentMap 

和Java 8

  Java.util.Map 

  putIfAbsent(K key,V value)
/ pre>

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



如果您需要对价值进行懒惰评估,则

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


I am sick of the following pattern:

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.

I'm sure something somewhere exists to avoid this, but my Googling efforts yielded nothing relevant. Any suggestions?

解决方案

The

java.util.concurrent.ConcurrentMap 

and from Java 8

Java.util.Map

has

putIfAbsent(K key, V value) 

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)并返回如果key不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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