How to Sort an ArrayList of Objects by Property in Java?
Last Updated :
23 Nov, 2022
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
- Using Comparator interface
- 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:
- In the below program, we've defined a CustomObject class with a String property, customProperty.
- We've also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty.
- In the main() method, we've created an array list of custom objects list, initialized with 5 objects.
- For sorting the list with the given property, we use the list's sort() method.
- 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);
}
}
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
- The custom object type class which is Student here will implement the Comparable class<Student>.
- 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
- 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>.
- 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);
}
}
}
OutputStudent 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]
Similar Reads
Java Program to Sort ArrayList of Custom Objects By Property Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares t
2 min read
Java Program to Sort Objects in ArrayList by Date The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Com
6 min read
How to Convert TreeMap to an ArrayList in Java? TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot
4 min read
How to Sort a TreeSet with User Defined Objects in Java? Comparator interface sorts the objects of user-defined classes. An object of the Comparator class is capable of comparing two objects of two different classes. Following function compare obj1 with obj2 TreeSet implements the SortedSet interface. So, duplicate values are not allowed.Objects in a Tree
3 min read
How to Avoid Duplicate User Defined Objects in TreeSet in Java? TreeSet class in Java is part of Javaâs collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted. As the Tr
5 min read
Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
How to Add Custom Class Objects to the TreeSet in Java? TreeSet is an implementation of the SortedSet interface in java that uses a red-black tree for storage. By default, It maintains an ascending order. It contains unique elements only. It doesn't allow null elements. Access and retrieval times are quite fast. To add the user-defined object into TreeSe
3 min read
Java Program to Sort the Elements of an Array in Descending Order Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Get Two Different Objects Into a TreeSet in Java In Java, TreeSet is a part of the Java Collection Framework and is located in the java.util package. It implements the NavigableSet interface and extends the AbstractSet and TreeSet is known for maintaining its elements in sorted order, either based on their natural order. This must be consistent wi
3 min read
Java Program to Sort Names in an Alphabetical Order For, sorting names in an Alphabetical order there are multiple ways to sort the array, like using inbuilt Arrays.sort() method or using normal sorting algorithms like the bubble sort, merge sort. Here let's use the bubble sort and inbuilt sort. Example: Input : Array[] = {"Sourabh", "Anoop, "Harsh",
3 min read