如何使用Java 8从对象列表中获取最小值和最大值

我喜欢上课:

public class Test { private String Fname; private String Lname; private String Age; // getters, setters, constructor, toString, equals, hashCode, and so on } 

List testList这样的List testList填充了Test元素。

如何使用Java 8获得最小和最大age值?

为简化起见,您应该使您的年龄为Integerint而不是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();