java lambda max_在Java中使用Lambda表达式查找Max
小編典典
該方法Comparator.comparing(…)旨在創(chuàng)建一個(gè)Comparator使用基于對(duì)象屬性的訂單進(jìn)行比較的。當(dāng)使用lambda表達(dá)式i
-> i(這是(int i) -> { return i;
}此處的簡(jiǎn)短寫(xiě)法)作為屬性提供程序函數(shù)時(shí),結(jié)果Comparator將比較值本身。這工作時(shí),要比較的對(duì)象有一個(gè) 自然秩序 的Integer了。
所以
Stream.of(1,2,4,3,5).max(Comparator.comparing(i -> i))
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
與…相同
Stream.of(1,2,4,3,5).max(Comparator.naturalOrder())
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
盡管后者更有效,因?yàn)樗鼘?duì)于具有自然順序的所有類(lèi)型都實(shí)現(xiàn)為單例(和實(shí)現(xiàn)Comparable)。
根本max不需要a 的原因Comparator是因?yàn)槟褂玫姆盒皖?lèi)Stream可能包含任意對(duì)象。
這允許(例如)使用它streamOfPoints.max(Comparator.comparing(p->p.x))來(lái)查找具有最大值的點(diǎn),x而Point其本身沒(méi)有自然順序。或者做類(lèi)似的事情streamOfPersons.sorted(Comparator.comparing(Person::getAge))。
使用專(zhuān)家時(shí),IntStream您可以直接使用自然順序,這可能會(huì)更有效:
IntStream.of(1,2,4,3,5).max()
.ifPresent(maxInt->System.out.println("Maximum number in the set is " + maxInt));
為了說(shuō)明“自然順序”與基于屬性的順序之間的區(qū)別:
Stream.of("a","bb","aaa","z","b").max(Comparator.naturalOrder())
.ifPresent(max->System.out.println("Maximum string in the set is " + max));
這將打印
集合中的最大字符串為z
因?yàn)镾trings 的自然順序是字典順序,其中z大于b大于大于a
另一方面
Stream.of("a","bb","aaa","z","b").max(Comparator.comparing(s->s.length()))
.ifPresent(max->System.out.println("Maximum string in the set is " + max));
將打印
集合中的最大字符串為aaa
如流中所有s aaa的最大
長(zhǎng)度String。這是一個(gè)預(yù)期的用例,Comparator.comparing使用方法引用時(shí)可以使其更具可讀性,即Comparator.comparing(String::length)幾乎可以說(shuō)明一切……
2020-11-01
總結(jié)
以上是生活随笔為你收集整理的java lambda max_在Java中使用Lambda表达式查找Max的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2g 双核电脑 linux,9208)(
- 下一篇: WordPress架构简单剖析