简体   繁体   English

Java Optional 如果对象不为 null - 返回方法结果,如果为 null - 返回默认值

[英]Java Optional if object is not null - returns the method result, if null - returns default value

Is it possible to transform this code to a Java 8 Optional one-line expression?是否可以将此代码转换为 Java 8 Optional 单行表达式?

long lastPollTime;
if (object != null) {
    lastPollTime = object.getTime();
} else {
    lastPollTime = 0;
}

ie if some object is not null, I need to call an object method and return its result, or else return 0. Optional.ofNullable().orElse() is not suitable, as it returns the object of the same type, but i need the result of the method call or some default value.即如果某个对象不为null,我需要调用一个对象方法并返回它的结果,否则返回Optional.ofNullable().orElse()不适合,因为它返回相同类型的对象,但我需要方法调用的结果或一些默认值。

A few forms:几种形式:

long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);

long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);

long lastPollTime = Optional.ofNullable(object).isPresent() ? object.getTime() : 0;

long lastPollTime = object != null ? object.getTime() : 0;

Of these, the last one, which doesn't use Optional (and therefore doesn't strictly answer your question!) is simpler to read and has fewer runtime overheads, and so should be preferred.其中,最后一个不使用 Optional (因此不能严格回答您的问题!)更易于阅读并且运行时开销更少,因此应该首选。

Arguably, it's even simpler if you reverse the options:可以说,如果您颠倒这些选项,那就更简单了:

long lastPollTime = object == null ? 0 : object.getTime();

... although you might prefer to have the default last -- it's a matter of personal taste. ...虽然您可能更喜欢最后使用默认值 - 这是个人品味的问题。


If you really can't use ternary operators, and you're doing this a lot, you could write your own utility method:如果你真的不能使用三元运算符,并且你经常这样做,你可以编写自己的实用方法:

public <T,U> U mapWithFallback(T obj, Function<T,U> function, U fallback) {
    if(obj == null) {
        return fallback;
    } else {
        return function.apply(obj);
    }
}

... callable as: ...可调用为:

long lastPollTime = mapWithFallback(object, o -> o.getTime(), 0);

... or make a complete mockery of your no-ternaries check using: ...或使用以下方法完全嘲笑您的无三元检查:

public <T,U> U ifElse( Supplier<Boolean> a, Supplier<U> ifTrue, Supplier<U> ifFalse) {
     if(a.get()) {
          return ifTrue.get();
     } else {
          return ifFalse.get();
     }
}

long lastPollTime = ifElse( () -> object == null, () -> object.getTime(), () -> 0);

It's in even better taste to avoid null references altogether, so that this kind of check isn't needed -- for example using the Null Object pattern .完全避免空引用更好,因此不需要这种检查——例如使用空对象模式

... or by writing methods that return Optional rather than potential nulls. ... 或者通过编写返回Optional而不是潜在空值的方法。 Optional is a great class; Optional是一个很棒的类; use it.用它。 Just don't convert something to Optional purely so you can immediately check whether it's empty.只是不要纯粹将某些内容转换为Optional以便您可以立即检查它是否为空。

long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);

您可以使用ClassOfObject::getTime类的方法引用,而不是o -> o.getTime()

long lastPollTime = object != null ?object.getTime():0;

you can do like below with java 8你可以像下面这样用java 8

long lastPollTime=Optional.ofNullable(object).isPresent()?object.getTime():0;

or without using java8 like this或者不使用这样的 java8

 long lastPollTime = object != null ?object.getTime():0;

Re ternary vs optional, if you ever needed to nest them the optional ends up being easier to read三元与可选,如果你需要嵌套它们,可选最终更容易阅读

long lastPollTime = Optional.ofNullable(object1)
  .map(o -> o.getTime())
  .orElse(Optional.ofNullable(object2)
    .map(o -> o.getTime())
    .orElse(0));

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

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