Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Sort an ArrayList of Objects by Property in Java?

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

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.

--> java.util Package
    --> ArrayList Class  

Syntax: Creating an empty ArrayList 

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

Different Ways  to Sort an ArrayList of Objects by Property

  1. Using Comparator interface
  2. Using Comparable interface

Approach 1: 

In this case, the comparator is a lambda which defines the below parameters as follows: 

  • 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 the greatest and stored back on to list.

Procedure:

  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.

Example

Java




// Java Program to Sort ArrayList of Objects by Property
 
// Importing required classes
import java.util.*;
 
// Class 1
// Custom class with custom property
// It takes and stores custom objects
class CustomObject {
 
     // Class data member
    private String customProperty;
 
    // Method
    public CustomObject(String property) {
        this.customProperty = property;
    }
 
    // Getter
    public String getCustomProperty() {
        return this.customProperty;
    }
}
 
// Class 2
public class GFG {
 
    // Method 1
    // To print sorted ArrayList objects
    // using enhanced for loop
    public static void print(ArrayList<CustomObject> list) {
       
        for (CustomObject obj : list) {
            System.out.println(obj.getCustomProperty());
        }
    }
 
    // Method 2
    // Comparing two list
    // using compareTo() method
    public static void sort(ArrayList<CustomObject> list) {
 
        list.sort((o1, o2)
                  -> o1.getCustomProperty().compareTo(
                      o2.getCustomProperty()));
    }
 
    // Method 3
    // Adding custom objects
    public static void add(ArrayList<CustomObject> list) {
 
        // Adding elements to list
        // using add() method
        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"));
    }
 
    // Method 4
    // Main driver method
    public static void main(String[] args) {
 
        // Creating an empty ArrayList of custom class type
        ArrayList<CustomObject> list = new ArrayList<>();
 
        // Calling above methods defined inside class
        // in main() method
        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 an error because it sorts only specific data-types and not user-defined types.

2-A: 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.

Example:

Java




// Java program to sort ArrayList of Custom Object
// Using Comparable class
 
// Importing required classes
import java.util.*;
 
// Class 1
// Main class
// ArrayListSorting
class GFG {
 
    // Main driver method
    public static void main(String args[]) {
 
        // Creating an empty ArrayList of Student type
        ArrayList<Student> arraylist
            = new ArrayList<Student>();
 
        // Adding elements to above List
        arraylist.add(new Student(12, "Riya", 15));
        arraylist.add(new Student(14, "Mahima", 16));
        arraylist.add(new Student(13, "Shubhi", 15));
 
        // Sorting above list using sort() method
        // of Collections class
        Collections.sort(arraylist);
 
        // Iterating over list via for each loop and
        // printing all elements inside the List
        for (Student str : arraylist) {
            System.out.println(str);
        }
    }
}
 
// Class 2
// Implementing Comparable interface
public class Student implements Comparable<Student> {
 
    // Class data members
    private String studentname;
    private int rollno;
    private int studentage;
 
    // Constructor of Student class
    public Student(int rollno, String studentname,
                   int studentage) {
 
        // this keyword refers to current instance itself
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
 
 
    // Getter and Setter methods
 
    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]

2-B: Sorting ArrayList with Comparator

  1. We will define another class that will implement the Comparator class of the 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.

Example:

Java




// Java Program to Sort ArrayList of Custom Object
// Using Comparator class
 
// Importing required classes
import java.util.*;
import java.util.Comparator;
 
// Class
public class Student {
 
    // Class data members
    private String studentname;
    private int rollno;
    private int studentage;
 
    // Constructor
    public Student(int rollno, String studentname,
                   int studentage) {
        // this keyword refers to current instance itself
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
 
    // Getters and Setters method
 
    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;
    }
 
    // Usage of comparator
    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
 
        // Comparing attributes of students
        public int compare(Student s1, Student s2) {
            String StudentName1
                = s1.getStudentname().toUpperCase();
            String StudentName2
                = s2.getStudentname().toUpperCase();
 
            // Returning in 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>() {
 
        // Method
        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;
        }
    };
 
    // Overriding toString() method to list out student details
    @Override public String toString() {
 
        return "[ rollno=" + rollno + ", name="
               + studentname + ", age=" + studentage + "]";
    }
}
 
// Class 2
// Main class
class Details {
 
    // Main driver method
    public static void main(String args[]) {
 
        // Creating an empty ArrayList of Student type
        ArrayList<Student> arraylist
            = new ArrayList<Student>();
 
        // Adding elements to ArrayList
        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:");
 
        // Using sort() method of Collection class
        Collections.sort(arraylist,
                         Student.StuNameComparator);
 
        for (Student str : arraylist) {
             
            System.out.println(str);
        }
 
        // Now, sorting on Rollno property
        System.out.println("RollNum Sorting:");
 
        Collections.sort(arraylist, Student.StuRollno);
 
        // Iterating over list via for each and
        // printing the elements
        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]
RELATED ARTICLES

Most Popular

Recent Comments