Java 可选如果对象不为 null - 返回方法结果,如果为 null - 返回默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41631611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Optional if object is not null - returns the method result, if null - returns default value
提问by mv200580
Is it possible to transform this code to java 8 Optional one-line expression?
是否可以将此代码转换为 java 8 可选的单行表达式?
long lastPollTime;
if (object != null) {
lastPollTime = object.getTime();
} else {
lastPollTime = 0;
}
i.e. if some object is not null, I need to call 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 method call or some default value.
即如果某个对象不为空,我需要调用对象方法并返回其结果,否则返回 0。 Optional.ofNullable().orElse() 不合适,因为它返回相同类型的对象,但我需要方法调用的结果或一些默认值。
采纳答案by slim
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
is a great class; use it. Just don't convert something to Optional
purely so you can immediately check whether it's empty.
...或者通过编写返回Optional
而不是潜在空值的方法。Optional
是一个很棒的班级;用它。只是不要将某些内容转换为Optional
纯粹的内容,以便您可以立即检查它是否为空。
回答by Jekin Kalariya
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;
回答by Null
long lastPollTime = object != null ?object.getTime():0;
回答by F. Lumnitz
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);
Instead of o -> o.getTime()
you could use a methods reference like ClassOfObject::getTime
而不是o -> o.getTime()
你可以使用方法参考ClassOfObject::getTime
回答by Vlad Bochenin
long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);