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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Vishwa
  • 607
  • 2
  • 11
  • 21
  • 1
    I hate to sound like a broken record, but... `What have you tried? Show us some code and a specific error or problem.` – Jashaszun Jun 26 '15 at 23:09
  • 1
    Since you specified, that you want to use Java 8, take a look at [`Streams`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html). You should be able to figure out the rest on your own. – Turing85 Jun 26 '15 at 23:10

2 Answers2

24

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();
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 1
    No need for the double-map; just mapToInt(Test::getAge), the unboxing will be done for you. – Brian Goetz Jun 27 '15 at 00:53
  • 2
    @BrianGoetz Not quite. Notice that `getAge` returns `String` not `int`. – Pshemo Jun 27 '15 at 02:07
  • 3
    Who writes domain objects that store numbers in strings? Sheesh. :) – Brian Goetz Jun 27 '15 at 15:04
  • 2
    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. – Brian Goetz Jun 27 '15 at 15:32
2

max age:

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

min age:

   testList.stream()
            .mapToInt(Test::getAge)
            .min();
lasclocker
  • 311
  • 3
  • 8