Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Sort Objects In Java Using Comparator

Here is the scenario. We want to sort the collection of Student objects according to the value of each object's lastName, firstName and studentId. Look at the example code below.

  package com.example.core.comparator;

  /**
   * This is the object that we will sort in this lesson.
   * 
   * @author Rolan Liwanag
   *
   */
  public class Student {

    private int studentId;
    private String lastName;
    private String firstName;
	
    public Student(int studentId, String lastName, 
        String firstName) {
      this.studentId = studentId;
      this.lastName = lastName;
      this.firstName = firstName;
	}
	
    public int getStudentId() {
      return studentId;
    }

    public void setStudentId(int studentId) {
      this.studentId = studentId;
    }

    public String getLastName() {
      return lastName;
    }

    public void setLastName(String lastName) {
      this.lastName = lastName;
    }

    public String getFirstName() {
      return firstName;
    }

    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }

  }
                           


The above code is the class Student. The instances of that class will be placed in a collection object and later on be sorted.

  package com.example.core.comparator;

  import java.util.Comparator;

  /**
   * This Comparator will sort the Student object instances 
   * in ascending order according to their firstName 
   * property.
   * 
   * @author Rolan Liwanag
   *
   */
  public class StudentComparatorForFirstName 
      implements Comparator {

	@Override
    public int compare(Student student1, Student student2) {
        return student1.getFirstName().compareTo(
            student2.getFirstName());
    }
}
                           


The above code is responsible for comparing the attribute firstName of the student object to the attribute firstName of another student object.

  package com.example.core.comparator;

  import java.util.Comparator;

  /**
   * This Comparator will sort the Student object instances 
   * in ascending order according to their lastName 
   * property.
   * 
   * @author Rolan Liwanag
   *
   */
  public class StudentComparatorForLastName 
      implements Comparator {

    @Override
    public int compare(Student student1, Student student2) {
      return student1.getLastName().compareTo(
          student2.getLastName());
    }
  }
                           


The above code is responsible for comparing the attribute lastName of the student object to the attribute lastName of another student object.

  package com.example.core.comparator;

  import java.util.Comparator;

  /**
   * This Comparator will sort the Student object instances 
   * in ascending order according to their studentId 
   * property.
   * 
   * @author Rolan Liwanag
   *
   */
  public class StudentComparatorForStudentId  
      implements Comparator {

    @Override
    public int compare(Student student1, Student student2) {
      return student1.getStudentId() 
          - student2.getStudentId();
    }
  }
                           


The above code is responsible for comparing the attribute studentId of the student object to the attribute studentId of another student object.

  package com.example.core.comparator;

  import java.util.Arrays;
  import java.util.Comparator;
  import java.util.List;

  /**
   * This Comparator will sort the Student object instances 
   * according to the list of comparators.
   * 
   * @author Rolan Liwanag
   *
   */
  public class StudentChainComparator 
      implements Comparator {
	
    private List> listComparators;

    @SafeVarargs
    public StudentChainComparator(
        Comparator... comparators) {
      this.listComparators = Arrays.asList(comparators);
    }
	
    @Override
    public int compare(Student student1, Student student2) {
      for (Comparator comparator : listComparators
          ) {
        int result = comparator.compare(student1, student2);
        if (result != 0) {
          return result;
        }
      }
      return 0;
    }
  }
                           


The code above will apply the sorting logic of each comparator in the order the comparators were passed in the constructor of this object.

  package com.example.core.comparator;

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

  public class SortTheStudents {

    public static void main(String[] args) {
      Student s1 = new Student(6, "Ccc", "aaa");
      Student s2 = new Student(5, "Ccc", "bbb");
      Student s3 = new Student(4, "Ccc", "ccc");
      Student s4 = new Student(3, "Ddd", "aaa");
      Student s5 = new Student(2, "Ddd", "aaa");
      Student s6 = new Student(1, "Bbb", "bbb");
      Student s7 = new Student(7, "Bbb", "aaa");
      Student s8 = new Student(8, "Aaa", "aaa");
		
      ArrayList studentList = new ArrayList();
      studentList.add(s1);
      studentList.add(s2);
      studentList.add(s3);
      studentList.add(s8);
      studentList.add(s7);
      studentList.add(s6);
      studentList.add(s4);
      studentList.add(s5);
		
      System.out.println("*** Before sorting:");
      for (Student student : studentList) {
        System.out.println(student.getLastName() + "    " 
            + student.getFirstName() + "    " 
            + student.getStudentId());
      }
		
      //sort the students by lastName, firstName, studentId
      Collections.sort(studentList, 
          new StudentChainComparator(
            new StudentComparatorForLastName(), 
            new StudentComparatorForFirstName(), 
            new StudentComparatorForStudentId()
          )
      );
      System.out.println("*** After sorting:");
      for (Student student : studentList) {
        System.out.println(student.getLastName() 
            + "    " + student.getFirstName() + "    " 
		    + student.getStudentId());
      }
      /*
       * The order in which we inserted the comparators to 
       * the chain comparator took precedence
       * over the latter comparators that were inserted. 
       */
    }
  }
                           


You can try rearranging the order of the comparators and see for yourself what happens. You can also try removing a comparator from the list of parameters to the chain comparator.


Back    Next