如果存在 Optional<> 则抛出异常

Throw an exception if an Optional<> is present

假设我想查看某个对象是否存在于流中,如果不存在,则抛出异常。我可以这样做的一种方法是使用 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"));

反过来呢?如果我想在找到任何匹配项时抛出异常:

String two = values.stream()
        .filter(s -> s.equals("two"))
        .findAny()
        .ifPresentThrow(() -> new RuntimeException("not found"));

我可以只存储 Optional,并在

之后进行 isPresent 检查:
Optional<String> two = values.stream()
        .filter(s -> s.equals("two"))
        .findAny();
if (two.isPresent()) {
    throw new RuntimeException("not found");
}

有什么方法可以实现这种 ifPresentThrow 的行为吗?尝试以这种方式抛出是一种不好的做法吗?

如果您的过滤器发现任何问题,您可以使用 ifPresent() 调用来抛出异常:

    values.stream()
            .filter("two"::equals)
            .findAny()
            .ifPresent(s -> {
                throw new RuntimeException("found");
            });

因为你只关心 if 找到匹配项,而不关心实际找到的是什么,你可以为此使用 anyMatch,你不需要使用Optional 全部:

if (values.stream().anyMatch(s -> s.equals("two"))) {
    throw new RuntimeException("two was found");
}
userOptional.ifPresent(user1 -> {throw new AlreadyExistsException("Email already exist");});

这里中括号是必须的,否则显示编译时异常

{throw new AlreadyExistsException("Email already exist");}

public class AlreadyExistsException extends RuntimeException

和异常class必须扩展运行时异常