简体   繁体   中英

NULL safe object checking in JAVA 8 using ifPresent

I have this function:

public static long toEpochMilli(OffsetDateTime dateTime) {
    return dateTime.toInstant().toEpochMilli();
}

that I want to use but I have to check before if it is null

private Long buildBookingValidDate (TimeIntervalType validFor) {

        return Optional.ofNullable(validFor.getStartTimeStamp())
                .ifPresent(DateUtils::toEpochMilli);

    }

but I don't know how to return the value

Here's how it would look in "normal" Java. Just for comparison.

private Long buildBookingValidDate (TimeIntervalType validFor) {
    if(validFor.getStartTimeStamp() == null)
        return null;

    return DateUtils.toEpochMilli(validFor.getStartTimeStamp());
}

I will recommend using .map and return Optional<Long> instead of null when input is null .

example using jshell ,

When input is some value,

jshell> import java.time.OffsetDateTime

jshell> Optional<OffsetDateTime> data = Optional.ofNullable(OffsetDateTime.now())
data ==> Optional[2019-09-08T23:36:48.470738-07:00]

jshell> data.map($ -> $.toInstant().toEpochMilli())
$2 ==> Optional[1568011008470]

When input is empty, it will return Optional.empty but client has to check if the output has value in it

jshell> Optional<OffsetDateTime> data = Optional.ofNullable(null)
data ==> Optional.empty

jshell> data.map($ -> $.toInstant().toEpochMilli())
$4 ==> Optional.empty

You are misusing Optional - it wasn't designed to replace null check.

If you still don't want to use plain, old Java for your case then you can create a helper method like

static <T, R> R applyIfNotNull(T obj, Function<T, R> function) {
    return obj != null ? function.apply(obj) : null;
}

and call it as follows

long time = applyIfNotNull(validFor.getStartTimeStamp(), FooBar::toEpochMilli);

and since you like so much Optional , you can use it in applyIfNotNull method:

static <T, R> Optional<R> applyIfNotNull(T obj, Function<T, R> function) {
    return obj != null ? Optional.of(function.apply(obj)) : Optional.empty();
}

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