简体   繁体   English

使用ifPresent在JAVA 8中进行NULL安全对象检查

[英]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. 这是“普通” 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 . 我会建议使用.map并返回Optional<Long> ,而不是null当输入为null

example using jshell , 使用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 当输入为空时,它将返回Optional.empty但客户端必须检查输出中是否有值

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. 您正在滥用Optional并非旨在取代null检查。

If you still don't want to use plain, old Java for your case then you can create a helper method like 如果您仍然不想使用普通的旧Java,则可以创建一个辅助方法,例如

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: 并且由于您非常喜欢Optional ,因此可以在applyIfNotNull方法中使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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