sort an arraylist of objects in java with code examples

Java provides a number of ways to sort an array of objects. In this article, we will explore the most common methods for sorting an ArrayList of objects in Java.

Method 1: Using the sort() method from the Collections class

The Collections class provides a sort() method that can be used to sort an ArrayList of objects. The method takes two parameters: the ArrayList to be sorted and a comparator object that defines the sorting order.

Here is an example of how to use the sort() method to sort an ArrayList of objects:

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

class Student {
    int rollNo;
    String name;
    int age;

    Student(int rollNo, String name, int age) {
        this.rollNo = rollNo;
        this.name = name;
        this.age = age;
    }
}

class SortByRoll implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.rollNo - b.rollNo;
    }
}

class SortByName implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name);
    }
}

class SortByAge implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.age - b.age;
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<Student>();
        students.add(new Student(1, "John", 22));
        students.add(new Student(2, "Bob", 20));
        students.add(new Student(3, "Mike", 21));

        System.out.println("Original Order:");
        for (Student student : students) {
            System.out.println(student.rollNo + " " + student.name + " " + student.age);
        }

        Collections.sort(students, new SortByRoll());
        System.out.println("\nSorted by RollNo:");
        for (Student student : students) {
            System.out.println(student.rollNo + " " + student.name + " " + student.age);
        }

        Collections.sort(students, new SortByName());
        System.out.println("\nSorted by Name:");
        for (Student student : students) {
            System.out.println(student.rollNo + " " + student.name + " " + student.age);
        }

        Collections.sort(students, new SortByAge());
        System.out.println("\nSorted by Age:");
        for (Student student : students) {
            System.out.println(student.rollNo + " " + student.name + " " + student.age);
        }
    }
}

In the above example, we have a class called Student that has three fields: rollNo, name, and age. We have created three comparator classes (SortByRoll, SortByName, and SortByAge) that implement the Comparator interface and define the sorting order for each field.

In the main method, we have
Method 2: Using the Comparable interface

Another way to sort an ArrayList of objects in Java is by implementing the Comparable interface in the class of the objects that are stored in the ArrayList. The Comparable interface has a single method called compareTo() that compares the current object with the one passed as a parameter and returns an int value indicating the relative order of the two objects.

Here is an example of how to use the Comparable interface to sort an ArrayList of objects:

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

class Employee implements Comparable<Employee> {
    int id;
    String name;
    int salary;

    Employee(int id, String name, int salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    public int compareTo(Employee e) {
        return this.id - e.id;
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<Employee>();
        employees.add(new Employee(1, "John", 50000));
        employees.add(new Employee(2, "Bob", 60000));
        employees.add(new Employee(3, "Mike", 40000));

        System.out.println("Original Order:");
        for (Employee employee : employees) {
            System.out.println(employee.id + " " + employee.name + " " + employee.salary);
        }

        Collections.sort(employees);
        System.out.println("\nSorted by ID:");
        for (Employee employee : employees) {
            System.out.println(employee.id + " " + employee.name + " " + employee.salary);
        }
    }
}

In the above example, we have a class called Employee that implements the Comparable interface. The compareTo() method compares the id field of the current object with the id field of the object passed as a parameter and returns an int value indicating the relative order of the two objects.

In the main method, we have created an ArrayList of Employee objects and added some employees to it. We then use the sort() method from the Collections class to sort the ArrayList. Since the Employee class implements the Comparable interface, the sort() method uses the compareTo() method to determine the sorting order.

Method 3: Using the Arrays.sort() method

Java also provides a sort() method in the Arrays class that can be used to sort an array of objects. The method takes two parameters: the array to be sorted and a comparator object that defines the sorting order.

Here is an example of how to use the Arrays.sort() method to sort an array of objects:

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

class Product {
    int id;
    String name;
    double price;

    Product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}

class SortById implements Comparator<Product> {
    public int compare(Product a, Product b) {
        return a.id - b.id;
    }

## Popular questions 
1. How can we sort an ArrayList of objects in Java using the Collections class?
Answer: We can use the sort() method from the Collections class, which takes two parameters: the ArrayList to be sorted and a comparator object that defines the sorting order.

2. What is the purpose of the Comparable interface in relation to sorting an ArrayList of objects in Java?
Answer: The Comparable interface has a single method called compareTo() that compares the current object with the one passed as a parameter and returns an int value indicating the relative order of the two objects. By implementing this interface in the class of the objects that are stored in the ArrayList, we can use the sort() method from the Collections class to sort the ArrayList using the compareTo() method.

3. How can we use the Arrays class to sort an array of objects in Java?
Answer: The Arrays class provides a sort() method that can be used to sort an array of objects. The method takes two parameters: the array to be sorted and a comparator object that defines the sorting order.

4. How can we sort an ArrayList of objects in Java based on a specific field of the objects?
Answer: We can create a comparator class that implements the Comparator interface and defines the sorting order based on a specific field of the objects. Then we can pass an instance of that comparator class to the sort() method from the Collections class.

5. Can we use the sort() method from the Collections class to sort an ArrayList of primitive data types?
Answer: No, the sort() method from the Collections class is only used to sort a list of objects, as it needs a comparator to determine the sorting order. To sort an array of primitive data types, we can use the sort() method from the Arrays class.

### Tag 
Java-Collections-Sorting
Posts created 2498

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top