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

19,927

Solution 1

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

Solution 2

max age:

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

min age:

   testList.stream()
            .mapToInt(Test::getAge)
            .min();
Share:
19,927
Vishwa
Author by

Vishwa

Updated on July 28, 2022

Comments

  • Vishwa
    Vishwa almost 2 years

    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> testList filled with Test elements.

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

  • Brian Goetz
    Brian Goetz almost 9 years
    No need for the double-map; just mapToInt(Test::getAge), the unboxing will be done for you.
  • Pshemo
    Pshemo almost 9 years
    @BrianGoetz Not quite. Notice that getAge returns String not int.
  • Brian Goetz
    Brian Goetz almost 9 years
    Who writes domain objects that store numbers in strings? Sheesh. :)
  • Brian Goetz
    Brian Goetz almost 9 years
    OK, but returning to the domain of useful, the point I was trying to make was: lambda conversion will do necessary adaptation like widening, boxing, casting, etc, to make up differences between the natural type of the lambda and the target type -- that one need not manually insert adaptations like unboxing.