`Optional.orElse()`和`Optional.orElseGet()`之间的区别 [英] Difference between `Optional.orElse()` and `Optional.orElseGet()`

查看:1385
本文介绍了`Optional.orElse()`和`Optional.orElseGet()`之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解 <之间的区别code>可选< T> .orElse() 可选< T> .orElseGet() 方法。

I am trying to understand the difference between the Optional<T>.orElse() and Optional<T>.orElseGet() methods.

orElse()方法的描述是如果存在则返回值,否则返回其他。

然而, orElseGet()方法的描述是返回值如果存在,否则调用other并返回该调用的结果。

orElseGet()方法采用供应商功能接口,基本上不接受任何参数并返回 T

The orElseGet() method takes a Supplier functional interface, which essentially does not take any parameters and returns T.

在哪种情况下你需要使用 orElseGet()?如果你有一个方法 T myDefault()你为什么不做 optional.orElse(myDefault())而不是 optional.orElseGet(() - > myDefault())

In which situation would you need to use orElseGet()? If you have a method T myDefault() why wouldn't you just do optional.orElse(myDefault()) rather than optional.orElseGet(() -> myDefault()) ?

它似乎不是 orElseGet()将lambda表达式的执行推迟到以后的某个时间或什么的,所以有什么意义呢? (我会认为如果它返回更安全的可选< T> ,其 get()会更有用从不抛出 NoSuchElementException isPresent()总是返回true ...但显然不是,它只返回 T 喜欢 orElse())。

It does not seem that orElseGet() is postponing the execution of the lambda expression to some later time or something, so what's the point of it? (I would have thought that it would be more useful if it returned a safer Optional<T> whose get() never throws a NoSuchElementException and isPresent() always returns true... but evidently its not, it just returns T like orElse()).

还有其他吗?差错我错过了吗?

Is there some other difference I am missing?

推荐答案

采取以下两种情况:

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

如果 opt 不包含值,这两者确实相当。但是如果 opt 确实包含一个值,那么将创建多少个 Foo 对象?

If opt doesn't contain a value, the two are indeed equivalent. But if opt does contain a value, how many Foo objects will be created?

Ps:当然在这个例子中,差异可能无法衡量,但如果您必须从远程Web服务获取默认值,例如,或者从数据库中突然变得非常重要。

这篇关于`Optional.orElse()`和`Optional.orElseGet()`之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆