Java可选,如果object不为null-返回方法结果,如果为null-返回默认值 [英] Java Optional if object is not null - returns the method result, if null - returns default value
问题描述
是否可以将此代码转换为Java 8可选单行表达式?
Is it possible to transform this code to a Java 8 Optional one-line expression?
long lastPollTime;
if (object != null) {
lastPollTime = object.getTime();
} else {
lastPollTime = 0;
}
即如果某个对象不为null,则需要调用一个对象方法并返回其结果,否则返回0. Optional.ofNullable().orElse()
不适合,因为它返回相同类型的对象,但是我需要方法调用的结果或某些默认值.
i.e. 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.
推荐答案
几种形式:
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;
其中,最后一个不使用Optional(因此不能严格回答您的问题!)更易于阅读,运行时开销也较小,因此应优先使用.
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.
可以说,如果您反转选项,它甚至更简单:
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);
}
}
...可调用为:
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);
完全避免使用空引用是一种更好的选择,因此不需要这种检查-例如,使用空对象模式.
...或编写返回 Optional
而不是可能为null的方法. Optional
是一个很好的类;用它.只是不要仅将某些内容转换为 Optional
,这样您就可以立即检查其是否为空.
... 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.
这篇关于Java可选,如果object不为null-返回方法结果,如果为null-返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!