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

编程入门 行业动态 更新时间:2024-10-12 08:16:02
本文介绍了Stream.max(Integer::max) : 意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为 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::max 和 Integer::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.

更多推荐

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

本文发布于:2023-11-22 01:13:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   Stream   max   Integer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!