문제

Is there a way to make the following code sample more concise?

final FluentIterable<AuthContext> withEmails = // ...               
final Optional<AuthContext> verified = withEmails.firstMatch(VERIFIED_EMAIL);

if (verified.isPresent()) {
    return verified.get();
}

return withEmails.first().orNull();

I was trying to do something like return verified.or(withEmails.first()) but there is no appropriate method in Optional.

Alternatively return verified.or(withEmails.first().orNull()) will fail when the orNull() method returns null.

도움이 되었습니까?

해결책

Just do verified.or(withEmails.first()).orNull();.

Depending on the return type of your method and your IDE of choice, the type inference may not suggest this as it returns another Optional of type T rather an a T itself.

c.f. Optional#or(Optional)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top