Stream.max(Integer :: max):意外的结果 [英] Stream.max(Integer::max) : Unexpected result

查看:1970
本文介绍了Stream.max(Integer :: max):意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 1z0-809:Java SE 8程序员II 使用Enthuware的模拟测试。

I'm studying for 1z0-809 : Java SE 8 Programmer II using Enthuware's mocktests.

遇到这个问题。


List<Integer> ls = Arrays.asList(3,4,6,9,2,5,7);

System.out.println(ls.stream().reduce(Integer.MIN_VALUE, (a, b)->a>b?a:b)); //1
System.out.println(ls.stream().max(Integer::max).get()); //2
System.out.println(ls.stream().max(Integer::compare).get()); //3
System.out.println(ls.stream().max((a, b)->a>b?a:b)); //4   

以上哪个陈述将打印9?

Which of the above statements will print 9?

答案是


1和3

1 and 3

但还有别的东西。我不明白为什么

But there is something else. I don't get why

System.out.println(ls.stream().max(Integer::max).get()); // PRINTS 3






我试图用它来调试它偷看但它无法让我理解。

我试图排序 ls 使用 Integer :: max Integer :: compare

ls.sort(Integer::max);     // [3, 4, 6, 9, 2, 5, 7]
ls.sort(Integer::compare); // [2, 3, 4, 5, 6, 7, 9]

当然,我得到 Integer :: max 不是比较器的事实,因此它具有相同的签名。
对我来说, max 在第一种情况下应该是 7 ,因为它是最后一个元素,就像我用Ìnteger进行排序::比较

Of course, I get the fact that Integer::max is not a Comparator, hence it has the same signature of one. For me, max should be 7 in the first case since it is the last element like when I sorted with Ìnteger::compare

有人可以将其分解为简单的东西吗?

Could someone break it down to something simple?

推荐答案

Integer.max(a,b)将返回给定<$ c的更大值$ c> a 和 b 。如果您以某种方式将该结果用作比较器,则返回的正值将被视为 a> b 所以 a 将被保留。

Integer.max(a, b) will return the greater value of the given a and b. If you use that result somehow as a comparator, a positive value returned will be regarded as meaning that a > b so a will be kept.

前两个元素是3和4两者都是积极的。 Integer.max(3,4)= 4> 0 。所以你实际上是在说 3> 4 使用这样的比较器,因此保留3个。然后,其余部分也是如此: Integer.max(3,6)= 6> 0 ,因此3被视为最大等等。

The first two elements are 3 and 4. Both are positive. Integer.max(3, 4) = 4 > 0. So you're effectively saying that 3 > 4 with such a comparator, so 3 is kept. Then, the same goes for the rest: Integer.max(3, 6) = 6 > 0, so 3 is considered the max, etc.

这篇关于Stream.max(Integer :: max):意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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