具有番石榴的对象列表中的object.attribute的最小值/最大值

问题描述 投票:0回答:3

让我们将Person列表定义为

  • name
  • 年龄

我想要一个List<Person>的最大(年龄)。

我可以迭代这个列表并手动保持最大值:

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

但是我觉得可能存在可以为我做的番石榴方法的组合。如果我写一个Function<Person, Integer>,是否有一个现成的方法来从列表中获取最大值?

java guava
3个回答
4
投票

this答案。你可以使用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);

1
投票

你可以用Guava做到这一点,但我认为它会比你的解决方案更清晰的版本更复杂,即:

int max = -1;

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

顺便说一句,把你的班级称为Person可能更有意义,因为它代表一个人,而不是一群人。


1
投票

如果你有一个Function<Person, Integer>(比方说叫getAge),那就是:

Integer maxAge = Ordering.natural().max(Iterables.transform(people, getAge));
© www.soinside.com 2019 - 2024. All rights reserved.