I have a person class with name and age:
public class Person {
private int age;
private String name;
}
Having a list of persons and a specific person X, I want to know the person Y that is the nearest to X by age (i.e. X.age - Y.age is the min of comparing to all others):
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
}
}
I want to use the Stream API but I don't know how, I tried the reduce but It doesn't work. Can anyone help?
Find the minimum difference between 2 numbers:
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);
}
You use the min(Comparator<? super T> comparator) method, e.g.
public Person process(Person pRef) {
return persons.stream()
.filter(p -> ! p.equals(pRef)) // never find pRef itself
.min((p1, p2) -> Integer.compare(Math.abs(p1.getAge() - pRef.getAge()),
Math.abs(p2.getAge() - pRef.getAge())))
.orElse(null);
}
where Math.abs(p1.getAge() - pRef.getAge()) is the age difference between p1 and the reference person, i.e. always a positive number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With