/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
orElse 如果value为空则返回other;
orElseGet如果为空则触发other.get()的调用;
本文深入探讨了Java中Optional类的orElse与orElseGet方法的使用场景及实现原理。详细解释了当Optional对象中存在值时直接返回该值,否则分别返回指定的默认值或通过 Supplier 接口提供的值的机制。
390

被折叠的 条评论
为什么被折叠?



