让我们将Person
列表定义为
我想要一个List<Person>
的最大(年龄)。
我可以迭代这个列表并手动保持最大值:
Integer max = null;
for(Person p : list) {
if(max == null || max < p.getAge()) {
max = p.getAge();
}
return max;
}
但是我觉得可能存在可以为我做的番石榴方法的组合。如果我写一个Function<Person, Integer>
,是否有一个现成的方法来从列表中获取最大值?
见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);
你可以用Guava做到这一点,但我认为它会比你的解决方案更清晰的版本更复杂,即:
int max = -1;
for (People p : list) {
if (p.getAge() > max)
max = p.getAge();
}
顺便说一句,把你的班级称为Person
可能更有意义,因为它代表一个人,而不是一群人。
如果你有一个Function<Person, Integer>
(比方说叫getAge
),那就是:
Integer maxAge = Ordering.natural().max(Iterables.transform(people, getAge));