Sam*_*Sam 18 java dictionary hashmap
我正在使用以下代码检查Map实例中是否存在密钥:
if (!map_instance.containsKey(key))
throw new RuntimeException("Specified key doesn't exist in map");
else
return map_instance.get(key);
Run Code Online (Sandbox Code Playgroud)
我的问题是:
是否有实用程序或Map实现来简化上述代码,例如:
custom_map.get(key,"Specified key doesn't exist in map");
Run Code Online (Sandbox Code Playgroud)
我的目标是:如果keymap中不存在,则map实现会使用传递的字符串抛出异常.
我不知道我的愿望是否合理?
(对不起,如果我使用错误的术语或语法,我仍在学习英语.)
Mar*_*ski 21
在Java 8中,您可以使用computeIfAbsentfrom Map,如下所示:
map.computeIfAbsent("invalid", key -> { throw new RuntimeException(key + " not found"); });
Run Code Online (Sandbox Code Playgroud)
Evg*_*nov 12
还有一种更好的方法可以实现这一目标:
return Objects.requireNonNull(map_instance.get(key), "Specified key doesn't exist in map");
Run Code Online (Sandbox Code Playgroud)
优点:
缺点:
NullPointerException- 有时NoSuchElementException或自定义异常更可取需要 Java 8
I use Optional Java util class, e.g.
Optional.ofNullable(elementMap.get("not valid key"))
.orElseThrow(() -> new ElementNotFoundException("Element not found"));
Run Code Online (Sandbox Code Playgroud)
您可以在这里查看来自apache commons的配置图.它没有工具Map,但与一些helper方法,像类似的界面getString,getStringArray,getShort等等.
使用此实现,您可以使用该方法,setThrowExceptionOnMissing(boolean throwExceptionOnMissing)并可以捕获它并根据需要进行处理.
不完全是一个可配置的消息,但从我的观点来看,仅使用自定义消息抛出一个固定的异常是没有意义的,因为异常类型本身取决于get调用该方法的上下文.例如,如果你执行一个用户的获取,异常将是与此相关的事情,也许UserNotFoundException,而不仅仅是一个RuntimeException消息:用户在地图中找不到!