这是什么意思?Java

huangapple go评论61阅读模式
英文:

What does it mean? Java

问题

something().orElseGet(() -> (a, b, c) -> {})
// ^----这部分------^

其中(a, b, c)是一个带有abc参数的方法,例如:Method(a, b, c),它返回了某些内容。

我的问题是,在实践中,这个函数接口部分是什么意思,对我来说很令人困惑。

英文:
something().orElseGet(() -> (a, b, c) -> {})
                   // ^----this part------^

where (a, b, c) is a method with a, b and c parameters. e.g: Method(a, b, c) which returns something.

My question is in practice what does this functional interface part, for me it's confusing.

答案1

得分: 3

它返回一个Supplier,然后提供三参数方法实现(a, b, c) -> {}

通常,Java中的所有方法参数在方法被调用时会立即求值。

这意味着,在假设的情况下orElseGet((a, b, c) -> {}),无论是否需要,该方法都将始终被创建。但由于仅在没有其他值存在时才需要它,使用中间的供应商意味着只有在实际需要时才会创建该方法。

由于在没有值存在的情况下使用的值可能在创建时成本很高,供应商可能是一个巨大的时间节省者。在您的情况下,可能不会有太大的区别(创建供应商或创建lambda在成本上可能是相等的)。但在其他情况下,获取值可能涉及数据库查找、字符串连接等操作,仅在实际需要时执行这些操作可能会带来巨大的好处。

英文:

It returns a Supplier that then supplies the three parameter method implementation (a, b, c) -> {}

Usually, all method parameters in Java are evaluated as soon as a method is called.

This means, that in the hypothetical case of orElseGet((a, b, c) -> {}) the method would always be created, whether it is needed or not. But as it is only needed when there is no other value present, having the intermediate supplier means that the method is only created when it is actually needed.

As the value that is used in the case that there is no value present might be arbitrarily costly to create, the supplier is potentially a huge time saver. In your case there will not be much of a difference (creating a supplier or creating a lambda is probably about equal in terms of cost). But there can be other situations where getting the value might involve database lookups, string concatenation etc, where it can be a huge benefit to only perform those actions when they are actually needed.

huangapple
  • 本文由 发表于 2020年10月13日 17:44:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64332706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定