9

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?

2
  • 1
    I hate to sound like a broken record, but... What have you tried? Show us some code and a specific error or problem. Commented Jun 26, 2015 at 23:09
  • 1
    Since you specified, that you want to use Java 8, take a look at Streams. You should be able to figure out the rest on your own. Commented Jun 26, 2015 at 23:10

2 Answers 2

26

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();
Sign up to request clarification or add additional context in comments.

4 Comments

No need for the double-map; just mapToInt(Test::getAge), the unboxing will be done for you.
@BrianGoetz Not quite. Notice that getAge returns String not int.
Who writes domain objects that store numbers in strings? Sheesh. :)
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.
2

max age:

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

min age:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.