Java 8 Stream - .max() 重复

Java 8 Stream - .max() with duplicates(Java 8 Stream - .max() 重复)

本文介绍了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.
}

集合myOjbects =/*获取集合*/;

然后我想从集合中获取一个具有最大步长值的 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.

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

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?

max() 函数的 Java 8 文档没有说明在这种情况下会发生什么.

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 可以看到当两个元素相等时,即 compare 返回 0,则返回第一个元素.因此,在您的情况下,将在具有最高 step 的集合 MyClass 对象中返回 first.

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() 重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java 8 Stream - .max() 重复

基础教程推荐