Stream.max() 如何处理相等?

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

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

问题描述

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

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

如果 Comparator 传递给 Stream 中有多个最大/最低"元素/javase/8/docs/api/java/util/stream/Stream.html#max-java.util.Comparator-" rel="noreferrer">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?

推荐答案

确实很难从文档中得出一个明确的声明.如果我们试图从Reduction"过程的一般描述和文档的类似提示中得出结论,总是会觉得我们可能做了太多的解释.

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,他是关于 Stream 的权威人士接口:

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

如果流是有序的(比如你从数组或列表中得到的流),它返回在多个最大元素的情况下最大的first元素;只有当流是无序的时,它才允许选择任意元素.

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的文档中没有做出这样明确的声明,但至少符合我们对实现的经验和知识(我们这些看过源代码的人).并且不要忘记,实际的考虑,因为通过 unordered().max(comparator) 说选择任何而不是第一个"与当前的事态相比,说选择第一个而不是任何一个"很容易" 如果允许 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() 如何处理相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Stream.max() 如何处理相等?

基础教程推荐