使用可选映射和过滤器重写 if 语句

Rewrite if-statement using Optional map and filter

我有一个接受 Optional<LocalDateTime> 的谓词,我想检查它是否存在并且 LocalDateTime 在当前日期之前。

我可以用 if 语句编写它,如下所示:

@Override
public boolean test(Optional<ResetPassword> resetPassword) {
    if (resetPassword.isPresent()) {
        if (!resetPassword.get().getValidUntil().isBefore(LocalDateTime.now())) {
            throw new CustomException("Incorrect date");
        }
        return true;
    }
    return false;
}

如何使用 Optional.mapOptional.filter 函数重写它?

你不应该使用 Optional 作为任何东西的参数。相反,您应该让您的函数采用 ResetPassword,并且仅在存在 Optional 的值时才调用它。 像这样:

public void test(ResetPassword resetPassword) {
    if (!resetPassword.getValidUntil().isBefore(LocalDateTime.now())) {
        throw new CustomException("Incorrect date");
    }
}

然后这样称呼它:

resetPasswordOptional
    .ifPresent(rp -> test(rp));

希望这篇文章对你有所帮助,另外,请注意你抛出的异常RuntimeException你的应用程序会在错误条件下崩溃。

 public boolean test(Optional<ResetPassword> resetPassword) {
        return resetPassword.isPresent() && resetPassword
                .map(ResetPassword::getValidUntil)
                .filter(localDateTime -> localDateTime.isBefore(LocalDateTime.now()))
                .orElseThrow(() -> new CustomException("Incorrect date")) != null;
    }