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

How to get minimum and maximum value from List of Objects using Java 8

我class喜欢:

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

和一个像 List<Test> testList 这样的列表,其中包含 Test 个元素。

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

为了简化事情,您可能应该将年龄设为 Integerint,而不是 Sting,但由于您的问题是关于 String age,因此此答案将基于 String类型。


假设 String age 保存表示整数范围内值的字符串,您可以简单地将它映射到 IntStream 并使用它的 IntSummaryStatistics like

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();