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

编程入门 行业动态 更新时间:2024-10-12 01:25:15
本文介绍了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)将返回给定 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):意外的结果

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

发布评论

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

>www.elefans.com

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