Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java 8 stream to calculate diference between two values and return the min

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?

like image 276
aName Avatar asked Dec 05 '25 14:12

aName


2 Answers

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);
}
like image 80
Oleksandr Pyrohov Avatar answered Dec 07 '25 04:12

Oleksandr Pyrohov


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.

like image 29
Andreas Avatar answered Dec 07 '25 02:12

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!