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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31083405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:04:57  来源:igfitidea点击:

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

javalistjava-8java-stream

提问by Vishwa

I have class like:

我有这样的课程:

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

and a list like List<Test> testListfilled with Testelements.

和一个List<Test> testList充满Test元素的列表。

How can I get minimum and maximum value of ageusing Java 8?

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

回答by Pshemo

To simplify things you should probably make your age Integeror intinstead of Sting, but since your question is about String agethis answer will be based on Stringtype.

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



Assuming that String ageholds String representing value in integer range you could simply map it to IntStreamand use its IntSummaryStatisticslike

假设String age持有字符串代表整数的范围值,你可以简单地把它映射到IntStream和使用它的IntSummaryStatistics

IntSummaryStatistics summaryStatistics = testList.stream()
        .map(Test::getAge)
        .mapToInt(Integer::parseInt)
        .summaryStatistics();

int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();

回答by lasclocker

max age:

最大值age

   testList.stream()
            .mapToInt(Test::getAge)
            .max();

min age:

分钟age

   testList.stream()
            .mapToInt(Test::getAge)
            .min();