Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 344
Vishwa Avatar asked Jun 26 '15 23:06

Vishwa


People also ask

How will you get the highest number present in a list using Java 8?

2. Using Stream. max() method. The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator .


2 Answers

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();
like image 191
Pshemo Avatar answered Sep 30 '22 14:09

Pshemo


max age:

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

min age:

   testList.stream()
            .mapToInt(Test::getAge)
            .min();
like image 39
lasclocker Avatar answered Sep 30 '22 14:09

lasclocker