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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:29:13  来源:igfitidea点击:

Throw an exception if an Optional<> is present

javajava-8

提问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 orElseThrowmethod:

假设我想查看流中是否存在对象,如果不存在,则抛出异常。我可以这样做的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 isPresentcheck 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 ifPresentThrowsort 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 anyMatchfor this, and you don't need to use Optionalat 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");
            });