java Map 中的密钥存在检查实用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11383649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Key existence checking utility in Map
提问by Sam
I'm using the following code for checking if a key exists in a Map
instance:
我正在使用以下代码检查Map
实例中是否存在密钥:
if (!map_instance.containsKey(key))
throw new RuntimeException("Specified key doesn't exist in map");
else
return map_instance.get(key);
My question is:
我的问题是:
Is there a utility or Map
implementation to simplify the above code, such as:
是否有实用程序或Map
实现来简化上述代码,例如:
custom_map.get(key,"Specified key doesn't exist in map");
My goal is: if key
does not exist in map, the map implementation throws an exception with the passed string.
我的目标是:如果key
地图中不存在,则地图实现将使用传递的字符串抛出异常。
I don't know whether or not my desire is reasonable?
不知道我的愿望是否合理?
(Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)
(对不起,如果我使用了错误的术语或语法,我仍在学习英语。)
采纳答案by Francisco Spaeth
You could take a look into the configuration map from Apache commons. It doesn't implements Map
, but has a similar interface with a few Helper methods, like getString
, getStringArray
, getShort
and so on.
您可以查看 Apache commons 中的配置映射。它没有工具Map
,但与一些helper方法,像类似的界面getString
,getStringArray
,getShort
等等。
With this implementation you could use the method setThrowExceptionOnMissing(boolean throwExceptionOnMissing)
and could catch it and handle as you want.
通过此实现,您可以使用该方法setThrowExceptionOnMissing(boolean throwExceptionOnMissing)
并可以根据需要捕获和处理它。
Isn't exactly with a configurable message but from my point of view it doesn't make sense to throw a fixed exception just with a custom message since the exception type itself depends on the context where the get
method is invoked. For example, if you perform a get of an user the exception would be something related to that, maybe UserNotFoundException
, and not just a RuntimeException
with the message: User not Found in Map!
不完全是可配置的消息,但从我的角度来看,仅使用自定义消息抛出固定异常是没有意义的,因为异常类型本身取决于get
调用方法的上下文。例如,如果您对用户执行 get 操作,则异常可能与此相关UserNotFoundException
,而不仅仅是RuntimeException
带有消息:用户未在地图中找到!
回答by Marcin Majkowski
In Java 8 you can use computeIfAbsent
from Map
, like this:
在 Java 8 中,您可以使用computeIfAbsent
from Map
,如下所示:
map.computeIfAbsent("invalid", key -> { throw new RuntimeException(key + " not found"); });
回答by Sir Montes
I use Optional Java util class, e.g.
我使用可选的 Java util 类,例如
Optional.ofNullable(elementMap.get("not valid key"))
.orElseThrow(() -> new ElementNotFoundException("Element not found"));
回答by mort
Such a method does not exist for a Map in Java. You could create it by extending the Map class of course or by creating a wrapper class that contains the map and a tryGet
method.
Java 中的 Map 不存在这种方法。您当然可以通过扩展 Map 类或通过创建包含地图和tryGet
方法的包装类来创建它。
C# however does have a such a method: Directory.TryGetValue()
然而 C# 确实有一个这样的方法: Directory.TryGetValue()
public class MyMap {
public Map<Object, Object> map = new HashMap<Object, Object>();
public Object tryGet(Object key, String msg) {
if(!map.containsKey(key))
throw new IllegalArgumentException(msg);
return map.get(key);
}
回答by Tomer
the way you are doing it is the way to go.
你正在做的事情就是要走的路。
as a side note, your code doesn't make much sense since you will always return true, maybe you meant:
作为旁注,您的代码没有多大意义,因为您将始终返回 true,也许您的意思是:
return map_instance.get(key);
回答by Evgeny Kharitonov
There is one more nice way to achieve this:
还有一种更好的方法可以实现这一目标:
return Objects.requireNonNull(map_instance.get(key), "Specified key doesn't exist in map");
Pros:
优点:
- pure Java - no libs
- no redundant Optional - less garbage
- 纯 Java - 没有库
- 没有多余的 Optional - 更少的垃圾
Cons:
缺点:
- only
NullPointerException
- sometimesNoSuchElementException
or custom exceptions are more desirable
- only
NullPointerException
- 有时NoSuchElementException
或自定义异常更可取
Java 8 required
需要 Java 8