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

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

问题描述

我试图了解 <代码>可选.orElse()可选的.orElseGet()方法.

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

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

虽然,orElseGet() 方法的描述是如果存在则返回值,否则调用其他并返回该调用的结果."

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 表达式的执行推迟到稍后的时间或其他时间,那么它有什么意义呢?(我本以为如果它返回一个更安全的 Optionalget() 从不抛出 NoSuchElementExceptionisPresent() 总是返回真...但显然不是,它只返回 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 does 包含一个值,将会创建多少个 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天全站免登陆