简体   繁体   中英

Chaining multiple Java Optionals

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);
    }
}

How do I optimise this code with chaining optionals and orElseGet. listing.getTimingRestrictions() returns Boolean, listing.getLastEntryTime() returns String & add method from List returns Boolean as well.

Why would you use Optional there?

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

would do the trick, as getTimingRestrictions is boolean and is a primitive type it shouldn't be null anyway.

If I got everything right... :

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

You can map the Optional to a completely different value , allowing you to chain null-checks:

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

In your case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM