链接多个Java可选选项

时间:2019-03-13 10:29:16

标签: java lambda java-8 optional

private void validatePGTimingRestrictions(
        Listing listing,
        ListingAutoVerificationResponse listingAutoVerificationResponse) {
    if (Optional.ofNullable(listing.getLastEntryTime()).isPresent()
            && Optional.ofNullable(listing.getTimingRestrictions()).isPresent()
            && !listing.getTimingRestrictions()) {
        listingAutoVerificationResponse.getRejectReasons()
                .add(ListingAutoVerificationErrorMessages.PG_LISTING_TIMING_ERROR);
    }
}

如何通过链接可选和orElseGet来优化此代码。 listing.getTimingRestrictions()返回Boolean,listing.getLastEntryTime()返回String,List的add方法也返回Boolean。

3 个答案:

答案 0 :(得分:3)

为什么在那里要使用Optional?

if (listing.getLastEntryTime() != null && !listing.getTimingRestrictions()) {
listingAutoVerificationResponse.getRejectReasons()
           .add(ListingAutoVerificationErrorMessages.PG_LISTING_TIMING_ERROR);
}

可以解决问题,因为getTimingRestrictions是布尔值,并且是原始类型,因此无论如何都不应该是null

答案 1 :(得分:2)

如果我没事的话...:

if(listing.getLastEntryTime() != null){
    Optional.ofNullable(listing.getTimingRestrictions())
            .filter(x -> !x)
            .ifPresent(x -> <do whatever you want with x here>)
}

答案 2 :(得分:1)

您可以映射Optional 映射到一个完全不同的值,从而可以链接空检查:

Object a, b, c;
....
Optional.ofNullable(a) // null-check for 'a'
    .map(x -> b) // null-check for 'b'
    .map(x -> c) // null-check for 'c'
    .ifPresent(x -> ...) // do something with a,b,c

在您的情况下:

Optional.ofNullable(listing.getLastEntryTime())
    .map(x -> listing.getTimingRestrictions())
    .filter(x -> !x)
    .ifPresent(x -> ... ); // do something with the listing