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

后端 未结 2 502
攒了一身酷
攒了一身酷 2020-12-11 06:25

I have class like:

public class Test {
    private String Fname;
    private String Lname;
    private String Age;
    // getters, setters, constructor, toSt         


        
相关标签:
2条回答
  • 2020-12-11 06:49

    max age:

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

    min age:

       testList.stream()
                .mapToInt(Test::getAge)
                .min();
    
    0 讨论(0)
  • 2020-12-11 07:06

    To simplify things you should probably make your age Integer or int instead of Sting, but since your question is about String age this answer will be based on String type.


    Assuming that String age holds String representing value in integer range you could simply map it to IntStream and use its IntSummaryStatistics like

    IntSummaryStatistics summaryStatistics = testList.stream()
            .map(Test::getAge)
            .mapToInt(Integer::parseInt)
            .summaryStatistics();
    
    int max = summaryStatistics.getMax();
    int min = summaryStatistics.getMin();
    
    0 讨论(0)
提交回复
热议问题