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