java comparator

java

In Java, the Comparator interface is used to compare objects of a specific type. It provides a way to define a custom ordering for a particular class, rather than using the default ordering provided by the class itself.

Here is an example of how to use the Comparator interface to define a custom comparison function for a Person class:

import java.util.Comparator;

public class Person {
  private String name;
  private int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }
}

class AgeComparator implements Comparator<Person> {
  @Override
  public int compare(Person p1, Person p2) {
    return p1.getAge() - p2.getAge();
  }
}

class NameComparator implements Comparator<Person> {
  @Override
  public int compare(Person p1, Person p2) {
    return p1.getName().compareTo(p2.getName());
  }
}

In this example, we have defined two comparator classes: AgeComparator and NameComparator. The AgeComparator class compares two Person objects based on their age, and the NameComparator class compares them based on their name.

You can use these comparator classes to sort a list of Person objects in a specific order. For example:

List<Person> people = Arrays.asList(
  new Person("Alice", 30),
  new Person("Bob", 25),
  new Person("Charlie", 35)
);

Collections.sort(people, new AgeComparator());

This will sort the list of Person objects in ascending order by age. To sort the list in descending order, you can use the Collections.reverseOrder method:

Collections.sort(people, Collections.reverseOrder(new AgeComparator()));

You can also use the Comparator.comparing method to create a comparator using a lambda expression:

Collections.sort(people, Comparator.comparing(Person::getAge));