Stream.max(Integer::max) : 意外结果

2022-01-22 00:00:00 max compare java-8 java java-stream

我正在为 1z0-809 : Java SE 8 Programmer II 使用 Enthuware 的模拟测试.

遇到这个问题.

<块引用>

列表<整数>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));//1System.out.println(ls.stream().max(Integer::max).get());//2System.out.println(ls.stream().max(Integer::compare).get());//3System.out.println(ls.stream().max((a, b)->a>b?a:b));//4

以上哪个语句会打印 9?

答案是

<块引用>

1 和 3

但还有别的.我不明白为什么

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


我尝试使用 peek 对其进行调试,但这并不能帮助我理解.

我尝试使用 Integer::maxInteger::compare

ls 进行排序

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

当然,我知道 Integer::max 不是比较器,因此它具有相同的签名.对我来说, max 在第一种情况下应该是 7 因为它是最后一个元素,就像我用 Integer::compare

有人能把它分解成简单的东西吗?

解决方案

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

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

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

Encountering this question.

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   

Which of the above statements will print 9?

Answer is

1 and 3

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

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


I tried to debug it using peek but it doesn't help me understanding.

I tried to sort ls using Integer::max and Integer::compare

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

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 Integer::compare

Could someone break it down to something simple?

解决方案

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.

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.

相关文章