链接多个 Java 可选

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

如何使用链接选项和 orElseGet 优化此代码。 listing.getTimingRestrictions() returns 布尔值,listing.getLastEntryTime() returns 字符串和列表中的添加方法 returns 布尔值。

为什么要在那里使用 Optional?

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

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

如果我做对了……:

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

您可以映射 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