Java 如果 Optional<> 存在则抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28596790/
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
Throw an exception if an Optional<> is present
提问by mkobit
Let's say I want to see if an object exists in a stream and if it is not present, throw an Exception. One way I could do that would be using the orElseThrow
method:
假设我想查看流中是否存在对象,如果不存在,则抛出异常。我可以这样做的orElseThrow
一种方法是使用该方法:
List<String> values = new ArrayList<>();
values.add("one");
//values.add("two"); // exception thrown
values.add("three");
String two = values.stream()
.filter(s -> s.equals("two"))
.findAny()
.orElseThrow(() -> new RuntimeException("not found"));
What about in the reverse? If I want to throw an exception if any match is found:
反过来呢?如果我想在找到任何匹配项时抛出异常:
String two = values.stream()
.filter(s -> s.equals("two"))
.findAny()
.ifPresentThrow(() -> new RuntimeException("not found"));
I could just store the Optional
, and do the isPresent
check after:
我可以只存储Optional
,并在isPresent
之后进行检查:
Optional<String> two = values.stream()
.filter(s -> s.equals("two"))
.findAny();
if (two.isPresent()) {
throw new RuntimeException("not found");
}
Is there any way to achieve this ifPresentThrow
sort of behavior? Is trying to do throw in this way a bad practice?
有没有办法实现这种ifPresentThrow
行为?试图以这种方式投掷是一种不好的做法吗?
采纳答案by Stuart Marks
Since you only care ifa match was found, not what was actually found, you can use anyMatch
for this, and you don't need to use Optional
at all:
由于您只关心是否找到匹配项,而不关心实际找到的内容,因此您可以使用anyMatch
它,而您根本不需要使用Optional
:
if (values.stream().anyMatch(s -> s.equals("two"))) {
throw new RuntimeException("two was found");
}
回答by beresfordt
You could use the ifPresent()
call to throw an exception if your filter finds anything:
ifPresent()
如果您的过滤器发现任何内容,您可以使用调用抛出异常:
values.stream()
.filter("two"::equals)
.findAny()
.ifPresent(s -> {
throw new RuntimeException("found");
});