Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to Sort an ArrayList of Objects by Property in Java?

  • Last Updated : 28 Dec, 2020

ArrayList in Java (equivalent to vector in C++) having a dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package.

ArrayList <E> list = new ArrayList <> ();

Approach 1:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  1. In the below program, we’ve defined a CustomObject class with a String property, customProperty.
  2. We’ve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty.
  3. In the main() method, we’ve created an array list of custom objects list, initialized with 5 objects.
  4. For sorting the list with the given property, we use the list‘s sort() method.
  5. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

In our case, the comparator is a lambda which-

  • Takes two objects from the list o1 and o2,
  • Compares the two object’s customProperty using compareTo() method,
  • And finally returns a positive number if o1’s property is greater than o2’s, negative if o1’s property is lesser than o2’s, and zero if they are equal.
  • Based on this, the list is sorted based on the least property to greatest and stored back to list.

Code:



Java




// Java program to sort the ArrayList
// of objects by property
  
import java.util.*;
  
// Define a custom class with custom property
// It takes and stores custom objects
class CustomObject {
  
    private String customProperty;
  
    public CustomObject(String property)
    {
        this.customProperty = property;
    }
  
    public String getCustomProperty()
    {
        return this.customProperty;
    }
}
  
public class GFG {
  
    // printing sorted ArrayList objects using enchanced
    // for loop
    public static void print(ArrayList<CustomObject> list)
    {
        for (CustomObject obj : list) {
            System.out.println(obj.getCustomProperty());
        }
    }
  
    // Comparison done using compareTo function
    public static void sort(ArrayList<CustomObject> list)
    {
  
        list.sort((o1, o2)
                      -> o1.getCustomProperty().compareTo(
                          o2.getCustomProperty()));
    }
  
    // Adding custom objects
    public static void add(ArrayList<CustomObject> list)
    {
        list.add(new CustomObject("Z"));
        list.add(new CustomObject("A"));
        list.add(new CustomObject("B"));
        list.add(new CustomObject("X"));
        list.add(new CustomObject("Aa"));
    }
  
    public static void main(String[] args)
    {
        // Declare ArrayList with custom class
  
        ArrayList<CustomObject> list = new ArrayList<>();
        add(list);
        sort(list);
        print(list);
    }
}
Output
A
Aa
B
X
Z

Approach 2: Using Comparable and comparator

When the ArrayList is of a custom object type, then in this case we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give error because it sorts only specific data-types and not user-defined types.

Sorting ArrayList with Comparable:

  1. The custom object type class which is Student here will implement the Comparable class<Student>.
  2. This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function.

Java




// Java program to sort ArrayList of
// custom object using Comparable class
  
import java.util.*;
class ArrayListSorting {
  
    public static void main(String args[])
    {
        ArrayList<Student> arraylist
            = new ArrayList<Student>();
        arraylist.add(new Student(12, "Riya", 15));
        arraylist.add(new Student(14, "Mahima", 16));
        arraylist.add(new Student(13, "Shubhi", 15));
  
        Collections.sort(arraylist);
  
        for (Student str : arraylist) {
            System.out.println(str);
        }
    }
}
  
public class Student implements Comparable<Student> {
    private String studentname;
    private int rollno;
    private int studentage;
  
    public Student(int rollno, String studentname,
                   int studentage)
    {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
  
    
    // getter and setter functions
    
    public String getStudentname() { return studentname; }
  
    public void setStudentname(String studentname)
    {
        this.studentname = studentname;
    }
  
    public int getRollno() { return rollno; }
  
    public void setRollno(int rollno)
    {
        this.rollno = rollno;
    }
  
    public int getStudentage() { return studentage; }
  
    public void setStudentage(int studentage)
    {
        this.studentage = studentage;
    }
  
    
    // overriding the compareTo method of Comparable class
    @Override public int compareTo(Student comparestu)
    {
        int compareage
            = ((Student)comparestu).getStudentage();
  
        //  For Ascending order
        return this.studentage - compareage;
  
        // For Descending order do like this
        // return compareage-this.studentage;
    }
  
    @Override public String toString()
    {
        return "[ rollno=" + rollno + ", name="
            + studentname + ", age=" + studentage + "]";
    }
}
Output
[ rollno=12, name=Riya, age=15]
[ rollno=13, name=Shubhi, age=15]
[ rollno=14, name=Mahima, age=16]

Sorting ArrayList with Comparator:

  1. We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>.
  2. This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list.

Java




// Java program to sort the ArrayList
// of custom object using Comparator class
  
import java.util.*;
import java.util.Comparator;
public class Student {
    private String studentname;
    private int rollno;
    private int studentage;
  
    public Student(int rollno, String studentname,
                   int studentage)
    {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
  
    // getter and setter functions
  
    public String getStudentname() { return studentname; }
  
    public void setStudentname(String studentname)
    {
        this.studentname = studentname;
    }
  
    public int getRollno() { return rollno; }
  
    public void setRollno(int rollno)
    {
        this.rollno = rollno;
    }
  
    public int getStudentage() { return studentage; }
  
    public void setStudentage(int studentage)
    {
        this.studentage = studentage;
    }
  
    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
               
      public int compare(Student s1, Student s2)
              {
  
                  String StudentName1
                      = s1.getStudentname().toUpperCase();
                  String StudentName2
                      = s2.getStudentname().toUpperCase();
  
                  // ascending order
                  return StudentName1.compareTo(
                      StudentName2);
  
                  // descending order
                  // return
                  // StudentName2.compareTo(StudentName1);
              }
          };
  
    // Comparator for sorting the list by roll no
    public static Comparator<Student> StuRollno = new Comparator<Student>() {
              public int compare(Student s1, Student s2)
              {
  
                  int rollno1 = s1.getRollno();
                  int rollno2 = s2.getRollno();
  
                  // For ascending order
                  return rollno1 - rollno2;
  
                  // For descending order
                  // rollno2-rollno1;
              }
          };
  
    @Override public String toString()
    {
        return "[ rollno=" + rollno + ", name="
            + studentname + ", age=" + studentage + "]";
    }
}
  
class Details {
  
    public static void main(String args[])
    {
        ArrayList<Student> arraylist
            = new ArrayList<Student>();
        
        arraylist.add(new Student(101, "Zues", 26));
        arraylist.add(new Student(505, "Abey", 24));
        arraylist.add(new Student(809, "Vignesh", 32));
  
        // Sorting based on Student Name
        System.out.println("Student Name Sorting:");
        
        Collections.sort(arraylist,
                         Student.StuNameComparator);
  
        for (Student str : arraylist) {
            System.out.println(str);
        }
  
        // Sorting on Rollno property
        System.out.println("RollNum Sorting:");
        
        Collections.sort(arraylist, Student.StuRollno);
        
        for (Student str : arraylist) {
            System.out.println(str);
        }
    }
}
Output
Student Name Sorting:
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
[ rollno=101, name=Zues, age=26]
RollNum Sorting:
[ rollno=101, name=Zues, age=26]
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]



My Personal Notes arrow_drop_up
Recommended Articles
Page :