[英]How to get minimum and maximum value from List of Objects using Java 8
我有這樣的課:
public class Test {
private String Fname;
private String Lname;
private String Age;
// getters, setters, constructor, toString, equals, hashCode, and so on
}
和List<Test> testList
這樣的List<Test> testList
填充了Test
元素。
如何使用Java 8獲得最小和最大age
值?
為了簡化一些事情,您應該使您的年齡為Integer
或int
而不是Sting,但由於您的問題是關於String age
因此這個答案將基於String
類型。
假設String age
保持String表示整數范圍內的值,您可以簡單地將其映射到IntStream
並使用其IntSummaryStatistics
IntSummaryStatistics summaryStatistics = testList.stream()
.map(Test::getAge)
.mapToInt(Integer::parseInt)
.summaryStatistics();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
最大age
:
testList.stream()
.mapToInt(Test::getAge)
.max();
最小age
:
testList.stream()
.mapToInt(Test::getAge)
.min();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.