Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31253

Min/Max of object.attribute in a list of object with guava

Let's take a list of Person defined as

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?

Upvotes: 0

Views: 3163

Answers (3)

n1k1ch
n1k1ch

Reputation: 2702

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

Upvotes: 4

ColinD
ColinD

Reputation: 110094

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

Integer maxAge = Ordering.natural().max(Iterables.transform(people, getAge));

Upvotes: 1

arshajii
arshajii

Reputation: 129537

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.

Upvotes: 1

Related Questions