-1

Say I have a class named Person.

class Person(){
    private int age;
}

And I have a List of Persons with ages 7, 2, 9, 4 and 17. I want to sort the list of Person objects in ascending order by the absolute difference of the Person's age with a given value.

For example, I want to sort the Persons based on the absolute difference of the Person's age and a given age say 7.

The result would be a List of Persons Objects with ages 7, 9, 4, 2, 17.

This is because

abs(7 - 7) = 0
abs(7 - 9) = 2
abs(7 - 4) = 3
abs(7 - 2) = 5
abs(7 - 17) = 10

As you can see I want to sort the list of Persons Objects based on the absolute difference of a given value (this value is not always the same).

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Please post what (code) you've tried and where you got stuck. – Kartik Feb 26 '19 at 05:35
  • I have not tried any code. After searching for the different ways to sort objects in Java, it appears that comparison is made between objects of the same type. I did not find any solution where I can pass in an argument and perform sorting based on the argument. – Chee Jing Jie Feb 26 '19 at 05:38
  • Comparisons can be made with instances of objects implementing the `Comparator` interface. So you will have to write a class that implements `Comparator` and takes some `targetAge` as constructor parameter. – Thomas Kläger Feb 26 '19 at 05:43
  • @CheeJingJie Start by finding out how to [sort a list of objects by class attribute](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property). When you can do that, it's easy enough to use `Math.abs(7 - person.getAge())` instead of `person.getAge()`. But try to make an attempt yourself. – ernest_k Feb 26 '19 at 05:45
  • I'm new to Java and interfaces so I did not really understand how the Comparator interface and the compare function works, sorry bout that. – Chee Jing Jie Feb 26 '19 at 06:06

2 Answers2

2
List<Person> people = ...;
people.sort(Comparator.comparingInt(p -> Math.abs(7 - p.getAge())));
Kartik
  • 7,677
  • 4
  • 28
  • 50
1

You could create a comparator class such as this one:

public class MyComparator implements Comparator<Person> {
    private final int refAge;

    public MyComparator(int refAge) {
        this.refAge = refAge;
    }

    @Override
    public int compare(Person p1, Person p2) {
        return Integer.compare(Math.abs(p1.getAge()-refAge),
                Math.abs(p2.getAge()-refAge));
    }
}

And then use it to sort your list:

    List<Person> persons = ...;
    Collections.sort(persons, new MyComparator(7));
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24