Java 8 Stream - .max() with duplicates(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.
}
集合
然后我想从集合中获取一个具有最大步长值的 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() 重复
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
