0

Let's take a list of Person defined as

  • Name
  • Surname
  • Age

I want the max(age) in a List<Person>.

I could iterate on this list and manually keep the max :

Integer max = null;
for(Person p : list) {
  if(max == null || max < p.getAge()) {
    max = p.getAge();
  }
  return max;
}

But I feel that there might exist a combination of Guava methods which can do it for me. If I write a Function<Person, Integer>, is there a ready-to-use method to get the max from the list?

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • Uh, what is `age`? I take it this is an `Integer` but why not make it an `int`? – fge Feb 21 '14 at 14:25
  • I like object because they can be null. If the age is not filled, I prefer getting a NPE (and be forced to add a constraint in DB) instead of having 0. – Arnaud Denoyelle Feb 21 '14 at 14:28
  • Uh, OK... But then why not force the code to have a value inserted in a first place? Hint: with null columns, how do you reliably use `NOT IN`? – fge Feb 21 '14 at 14:30
  • @fge It is a personal choice. On all the beans of my current project, I only write the attributes and generate Getters/Setters + a default constructor. I personnally hate Setters that do other than just setting a value. For `NOT IN`, I admit that I have never tried to use it on an optional column. – Arnaud Denoyelle Feb 21 '14 at 14:40

3 Answers3

4

See this answer. You can use Ordering.max()

Ordering<People> o = new Ordering<People>() {
    @Override
    public int compare(People left, People right) {
        return Ints.compare(left.getAge(), right.getAge());
    }
};

return o.max(list);
Jurn Ho
  • 69
  • 1
  • 5
n1k1ch
  • 2,594
  • 3
  • 31
  • 35
1

You can do it with Guava, but I think it would come out to be more convoluted than a cleaner version of your solution, namely:

int max = -1;

for (People p : list) {
    if (p.getAge() > max)
        max = p.getAge();
}

By the way, it may make more sense to call your class Person, since it is representing a single person, and not a group of people.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

If you have a Function<Person, Integer> (called getAge, say), this would just be:

Integer maxAge = Ordering.natural().max(Iterables.transform(people, getAge));
ColinD
  • 108,630
  • 30
  • 201
  • 202