我有一个具有姓名和年龄的人类:
public class Person {
private int age;
private String name;
}
有一个人列表和一个特定的人X,我想知道按年龄最接近X的人Y(即X.age-Y.age是与所有其他人进行比较的最小值):
public class Test {
List<Pearson> persons // suppose this list contains elements
public int calculate (Person p1, Person p2) {
return Math.abs(p1.getAge() - p2.getAge());
}
public Person process(Perosn X) {
int nearest persons.stream()... // need help
}
}
我想使用Stream API,但我不知道如何,我尝试了reduce,但是它不起作用。有人可以帮忙吗?
找到两个数字之间的最小差:
public Person process(Person px) {
int age = px.getAge();
return persons.stream()
.filter(p -> !p.equals(px))
.min(Comparator.comparingInt(p -> Math.abs(p.getAge() - age)))
.orElse(null);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句