Java 8可选如何处理太多orElses

时间:2016-11-08 10:06:41

标签: java lambda java-8 optional

让我们看一下没有lambdas的例子:

Credentials credentials = CredentialService.get(id);
if (credentials != null && credentials.isActive()) {
    User user = UserService.get(credentials.getUserId());
    if (user != null)
        return Status.ok(user);
}
return Status.bad();

如您所见,仅当用户不是Status.ok()时,才会返回null。否则,将返回Status.bad()。现在使用lambdas(Service的方法现在返回Optional<T>):

return CredentialService.get(id)
        .filter(Credentials::isActive)
        .map(credentials -> UserService.get(credentials.getUserId())
            .map(Status::ok)
            .orElse(Status.bad())              
        ).orElse(Status.bad());

现在我必须两次返回Status.bad()(实际代码,大约4-5)。这是一次返回Status.bad()的方法吗?

1 个答案:

答案 0 :(得分:7)

我可以猜测UserService :: get return在这种情况下,你最好使用flatMap:

CredentialService.get(id)
         .filter(Credentials::isActive)
            .flatMap(credentials -> UserService.get(credentials.getUserId())
            .map(Status::ok)
            .orElse(Status.bad())