Java 8 Stream - .max()带有重复项 [英] Java 8 Stream - .max() with duplicates

查看:4969
本文介绍了Java 8 Stream - .max()带有重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一组对象,它们的步长变量可以是1-4。

So I have a collection of objects that have a step variable that can be 1 - 4.

public class MyClass {
    private Long step;

    //other variables, getters, setters, etc.
}

收集和LT; MyClass的> myOjbects = / * get collection * /;

然后我想获得一个 MyClass 来自具有最大步长值的集合,所以我这样做:

Then I would like to get one instance of MyClass from the collection that has the maximum step value, so I do:

final Optional<MyClass> objectWithMaxStep =
   myObjects.stream().max(Comparator.comparing(MyClass::getStep));

但是,有些情况会有多个 MyClass 集合中等于4的实例。

However, there are situations where there will be multiple MyClass instances in the collection that have a step equal to 4.

所以,我的问题是,如何确定在<$ c $中返回哪个实例c>可选,或者当流中的多个对象具有要比较的最大值时是否抛出异常?

So, my question is, how is it determined which instance is returned in the Optional, or does it throw an exception when multiple objects in the stream have the max value that is being compared?

Java 8 max()函数的文档没有指定在这种情况下会发生什么。

The Java 8 documentation for the max() function does not specify what will occur in this situation.

推荐答案

max 实现了使用 maxBy 减少集合:

max is implemented reducing the collection with maxBy:

 public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
    }

这里 comparator.compare(a,b)> ; = 0? a:b 你可以看到当2个元素相等时,即 compare 返回0,然后返回第一个元素。因此,在您的情况下, first 将在 MyClass 集合中返回步骤

Here comparator.compare(a, b) >= 0 ? a : b you can see that when 2 elements are equal, i.e. compare returns 0, then the first element is returned. Therefore in your case will be returned first in a collection MyClass object with highest step.

更新:用户 the8472 在注释中正确提到,您不应该依赖javadocs未明确指定的实现。但是你可以在 max 方法上编写单元测试,以了解标准java库中的逻辑是否已经改变。

UPDATE: As user the8472 correctly mentioned in comments, you shouldn't rely on implementation which isn't explicitly specified by javadocs. But you can write unit test on max method to know if it's logic has changed in standard java library.

这篇关于Java 8 Stream - .max()带有重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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