Stream.max()如何处理相等性? [英] How does Stream.max() handle equality?

查看:199
本文介绍了Stream.max()如何处理相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我怀疑答案是未指定...

Although I suspect the answer to be "It's not specified"...

如果流将 Comparator 传递给 max min 方法认为相等(返回 0 ),是否指定了哪个元素会被找到?

If there are multiple "greatest/lowest" elements in a Stream which the Comparator passed to the max or min methods considers equal (returns 0), is it specified somewhere which element will be found?

推荐答案

确实很难从仅限文档。如果我们试图从减少过程的一般描述和文档的类似提示中得出结论,那么总会觉得我们可能做了太多的解释。

It’s indeed hard to pull a definite statement from the documentation only. If we try to draw a conclusion from the general description of the "Reduction" process and similar hints of the documentation, it will always feel like we’re possibly doing too much interpretation.

但是,有一个关于此问题的明确声明来自 Brian Goetz ,他们对此流程非常权威API:

However, there’s an explicit statement regarding this matter from Brian Goetz who’s quite an authority regarding the Stream API:


如果订购了流(例如从数组或列表中获取的流),它将首先返回 元素,在多个最大元素的情况下是最大的;只有当流是无序的时才允许选择一个任意元素。

If the stream is ordered (such as the streams you get from an array or List), it returns the first element that is maximal in the event of multiple maximal elements; only if the stream is unordered is it allowed to pick an arbitrary element.

遗憾的是这样的显式语句没有被制作出来在 Stream.max 的文档中,但至少它符合我们的实施经验和知识(我们这些查看源代码的人)。不要忘记,实际的考虑,因为很容易说选择任何而不是第一通过无序()。max(比较)与当前的事态而不是说先选择而不是任何如果 max 被允许首先选择一个任意元素。

It’s a pity that such an explicit statement isn’t made right at the documentation of Stream.max, but at least it’s in line with our experience and knowledge of the implementation (those of us who looked at the source code). And not to forget, practical considerations, as it’s easy to say "pick any rather than first" via unordered().max(comparator) with the current state of affairs than saying "pick first rather than any" if max was allowed to pick an arbitrary element in the first place.

这篇关于Stream.max()如何处理相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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