Comparing and sorting object with Comparator

By implementing Comparator interface in Java application, you can compare objects by custom rules.

Implementing compare() method

Compare method of the Comparator interface must be implemented. It provides two objects as arguments, which are compared according to your implementation. Notice that method returns negative, zero or positive integer values.
Negative value is returned if first argument is less than second argument.
Zero is returned if objects are equal.
Positive value is returned if first argument is more than second argument.

We will implement two comparators - first will sort persons according to the firstname and the second will sort persons according to the lastname.

package my.project.lists.comparator;

import java.util.Comparator;

public class FirstnameComparator implements Comparator<Person> {

@Override
public int compare(Person o1, Person o2) {
return o1.getFirstName().compareTo(o2.getFirstName());
}

}

package my.project.lists.comparator;

import java.util.Comparator;

public class LastnameComparator implements Comparator<Person> {

@Override
public int compare(Person o1, Person o2) {
return o1.getLastName().compareTo(o2.getLastName());
}
}

Run the comparator test

package my.project.lists.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorTest {

public static void main(String[] args) {

List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Al", "Pacino"));
persons.add(new Person("Sean", "Connery"));
persons.add(new Person("Robert", "De Niro"));
persons.add(new Person("Michael", "Douglas"));
persons.add(new Person("Brad", "Pitt"));

System.out.println("--- Unsorted");
for (int i = 0; i < persons.size(); i++) {
System.out.println(persons.get(i));
}

System.out.println("--- Sorted by firstname");
Collections.sort(persons, new FirstnameComparator());
for (int i = 0; i < persons.size(); i++) {
System.out.println(persons.get(i));
}

System.out.println("--- Sorted by lastname");
Collections.sort(persons, new LastnameComparator());
for (int i = 0; i < persons.size(); i++) {
System.out.println(persons.get(i));
}

}

}