如何使用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
值?
为简化起见,您应该使您的年龄为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();