May 24, 2022

How to Sort ArrayList of Objects in Java

In this post we’ll see how to sort ArrayList of objects in Java. In the post How to Sort ArrayList in Java we have already seen how you can sort ArrayList of String, Date or any Wrapper class (Integer, Float etc.). All those classes already implement Comparable interface so you just need to pass the list to Collections.sort() method to sort it.

When you need to sort ArrayList of custom objects in Java, you will have to make sure that the class whose objects are stored in the ArrayList implements Comparable interface or you have a Comparator implementation ready to be used.

Implementation of the Comparable interface will set the natural ordering of the class. If you want to sort in any other order rather than natural ordering set by Comparable then you can implement Comparator and use the sort() method of the Collections class which takes Comparator as argument.

If your class doesn’t implement Comparable interface and Comparator is also not specified then using an ArrayList of such objects with sort() method will result in compile time error.

sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified Comparator.

Sorting ArrayList of objects using Comparable

Here we have a class Employee and you want to sort by empName field of the class. Then Employee class should implement the Comparable interface and provide implementation of the compareTo() method.

public class Employee implements Comparable{
  private int empId;
  private String empName;
  private int age;
  Employee(int empId, String empName, int age){
    this.empId = empId;
    this.empName = empName;
    this.age = age;
  }
  public int getEmpId() {
    return empId;
  }
  public void setEmpId(int empId) {
    this.empId = empId;
  }
  public String getEmpName() {
    return empName;
  }
  public void setEmpName(String empName) {
    this.empName = empName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
    
  @Override
  public String toString() {    
    return getEmpId() + " " + getEmpName() + " " + getAge();
  }
  @Override
  public int compareTo(Employee o) {
    // Sort by empName in ascending order alphabetically
    return this.getEmpName().compareTo(o.getEmpName());
    /// sort by ascending order of age
    ///return this.getAge() - o.getAge();
  }  
}

Then you can pass ArrayList of Employee class object in Collections.sort() method.

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

public class SortingObjList {
  public static void main(String[] args) {
    List<Employee> empList = new ArrayList<Employee>();
    empList.add(new Employee(1, "Zhiang", 34));
    empList.add(new Employee(2, "Marie", 23));
    empList.add(new Employee(3, "Amy", 31));
    empList.add(new Employee(4, "Robbie", 45));
    empList.add(new Employee(5, "Dean", 26));
    System.out.println("**List elements**");
    for(Employee emp : empList) {
     System.out.println("" + emp);
    }
    // Sorting the list
    Collections.sort(empList);
    System.out.println("**Sorted List**");
    for(Employee emp : empList) {
      System.out.println("" + emp);
    }
  }
}
Output
**List elements**
1 Zhiang 34
2 Marie 23
3 Amy 31
4 Robbie 45
5 Dean 26
**Sorted List**
3 Amy 31
5 Dean 26
2 Marie 23
4 Robbie 45
1 Zhiang 34

Sorting ArrayList of objects using Comparator

Employee class used above implements Comparable and provide implementation of the compareTo() method to sort by name. This sort order becomes the natural ordering of the class but now you are bound with that ordering. What if you want to sort by age now? Answer is write a separate method or class implementing Comparator interface. By implementing Comparator you can have more than one option for sorting.

Here is the updated Employee class with 2 Comparator implementations added to sort by age or to sort by name in reverse order.

import java.util.Comparator;

public class Employee implements Comparable<Employee>{
  private int empId;
  private String empName;
  private int age;
  Employee(int empId, String empName, int age){
    this.empId = empId;
    this.empName = empName;
    this.age = age;
  }
  public int getEmpId() {
    return empId;
  }
  public void setEmpId(int empId) {
    this.empId = empId;
  }
  public String getEmpName() {
    return empName;
  }
  public void setEmpName(String empName) {
    this.empName = empName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
    
  @Override
  public String toString() {    
    return getEmpId() + " " + getEmpName() + " " + getAge();
  }
  @Override
  public int compareTo(Employee o) {
    // Sort by empName in ascending order alphabetically
    return this.getEmpName().compareTo(o.getEmpName());
    /// sort by ascending order of age
    ///return this.getAge() - o.getAge();
  }
    
  static Comparator<Employee> empCompByAge = new Comparator<Employee>() {
    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getAge() - emp2.getAge();
    }        
  };

  static Comparator<Employee> empCompByNameDesc = new Comparator<Employee>() {
    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp2.getEmpName().compareTo(emp1.getEmpName());
    }        
  }; 
}
Then you can pass these Comparator implementations with the sort() method to get the required ordering.
public class SortingObjList {
  public static void main(String[] args) {
    List<Employee> empList = new ArrayList<Employee>();
    empList.add(new Employee(1, "Zhiang", 34));
    empList.add(new Employee(2, "Marie", 23));
    empList.add(new Employee(3, "Amy", 31));
    empList.add(new Employee(4, "Robbie", 45));
    empList.add(new Employee(5, "Dean", 26));
    System.out.println("**List elements**");
    for(Employee emp : empList) {
      System.out.println("" + emp);
    }
    // Sorting the list by employee age
    Collections.sort(empList, Employee.empCompByAge);
    System.out.println("**Sorted List**");
    for(Employee emp : empList) {
      System.out.println("" + emp);
    }
         
    // Sorting the list by employee name in reverse order
    Collections.sort(empList, Employee.empCompByNameDesc);
    System.out.println("**Sorted List**");
    for(Employee emp : empList) {
      System.out.println("" + emp);
    }
  }
}
Output
**List elements**
1 Zhiang 34
2 Marie 23
3 Amy 31
4 Robbie 45
5 Dean 26
**Sorted List by age**
2 Marie 23
5 Dean 26
3 Amy 31
1 Zhiang 34
4 Robbie 45
**Sorted List**
1 Zhiang 34
4 Robbie 45
2 Marie 23
5 Dean 26
3 Amy 31

That's all for the topic How to Sort ArrayList of Objects in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment