我正在使用以下代码检查 Map
实例中是否存在键:
if (!map_instance.containsKey(key))
throw new RuntimeException("Specified key doesn't exist in map");
else
return map_instance.get(key);
我的问题是:
有没有实用工具或者Map
实现来简化上面的代码,比如:
custom_map.get(key,"Specified key doesn't exist in map");
我的目标是:如果 key
不存在于 map 中,map 实现将抛出传递的字符串异常。
不知道自己的愿望是否合理?
(抱歉,如果我使用了错误的术语或语法,我仍在学习英语。)
最佳答案
我使用可选的 Java util 类,例如
Optional.ofNullable(elementMap.get("not valid key"))
.orElseThrow(() -> new ElementNotFoundException("Element not found"));
关于java - map 中的关键存在检查实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11383649/