Sort ArrayList in Java

Sort ArrayList in Java | Sorting is an operation that assembles all the array elements in ascending or descending order. There is a build-in method available in Java Collections class to sort the array elements called sort(). There are various sort operations like the bubble sort, selection sort, merge sort, heap sort, insertion sort.

Sort ArrayList Of Objects Java

Step-1: Define a custom class with a custom property that takes and stores custom objects. Here we are creating a Student class that has roll number and name fields, both of them are private. To access the fields we will define getters and setters methods. And to display the student object we will override the toString() method.

class Student {

   private int no;
   private String name;

   // constructor
   public Student(int no, String name) {
      this.no = no;
      this.name = name;
   }

   // getters and setters method
   public int getNo() {
      return no;
   }

   public void setNo(int no) {
      this.no = no;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   // toString to display the object
   @Override
   public String toString() {
      return "Student [no=" + no + ", name=" + name + "]";
   }
}
  • Step 2: Create a Main class and Import the ArrayList class from the util package.
  • Step 3: Create an ArrayList object and add some student objects.
  • Step 4: Sort based on the student name, and display the ArrayList.
  • Step 5: Sort based on student roll number, and display the ArrayList.
import java.util.ArrayList;

public class Main {

   public static void main(String[] args) {
      // declare ArrayList with custom class
      ArrayList<Student> list = new ArrayList<>();

      // add custom objects in ArrayList
      list.add(new Student(200, "Amelia"));
      list.add(new Student(110, "John"));
      list.add(new Student(105, "William"));
      list.add(new Student(106, "Rocco"));
      list.add(new Student(120, "Jerry"));
      // display ArrayList
      System.out.println("Before Sorting: ");
      System.out.println(list);

      // sort ArrayList based on name
      list.sort((a1, a2) -> a1.getName().compareTo(a2.getName()));

      // display ArrayList
      System.out.println("Sorting based on name: ");
      System.out.println(list);

      // sort ArrayList based on roll number
      list.sort((a1, a2) -> a1.getNo() - a2.getNo());

      // display ArrayList
      System.out.println("Sorting based on no: ");
      System.out.println(list);
   }
}

Output:-

Before Sorting:
[Student [no=200, name=Amelia], Student [no=110, name=John], Student [no=105, name=William], Student [no=106, name=Rocco], Student [no=120, name=Jerry]]

Sorting based on name:
[Student [no=200, name=Amelia], Student [no=120, name=Jerry], Student [no=110, name=John], Student [no=106, name=Rocco], Student [no=105, name=William]]

Sorting based on no:
[Student [no=105, name=William], Student [no=106, name=Rocco], Student [no=110, name=John], Student [no=120, name=Jerry], Student [no=200, name=Amelia]]

While sorting based on name, we have called the compareTo() method because the String class overrides the compareTo() method to compare two string objects based on their content. But while sorting based on a roll no, we have written our own logic because it is “int” type which is a primitive data type.

Java Sort ArrayList Of Objects Using Collections.sort()

If we want to sort objects by using the Collections.sort() method then the class should be Comparable type i.e. it should implement the Comparable interface. Comparable is an interface in java that provides a single sorting sequence.

In this we sort array based on the objects, we have two classes User and Main where the user implements a comparable, and Main uses the user to print the sorted array. Sorting is done based on the id.

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

class User implements Comparable<User> {

   int id;
   String name;

   public User(int id, String name) {
      this.id = id;
      this.name = name;
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String toString() {
      return id + ":" + name;
   }

   @Override
   public int compareTo(User user) {
      // sort based on id
      return this.id - user.getId();
      // sort based on name
      // return this.name.compareTo(user.name);
   }

}

public class Main {
   public static void main(String[] args) {
      List<User> users = new ArrayList<User>();
      users.add(new User(2, "Robert"));
      users.add(new User(1, "James"));
      users.add(new User(3, "Harry"));
      users.add(new User(4, "Amellia"));
      System.out.println(users);

      Collections.sort(users);
      System.out.println(users);
   }
}

Output on sorting based on ID:-

[2:Robert, 1:James, 3:Harry, 4:Amellia]
[1:James, 2:Robert, 3:Harry, 4:Amellia]

Output on sorting based on the name:-

[2:Robert, 1:James, 3:Harry, 4:Amellia]
[4:Amellia, 3:Harry, 1:James, 2:Robert]

Java Sort ArrayList Of Integers

In this section, we will sort ArrayList of integer values. For this, we have two options:- sort in ascending order, or sort in descending order. To sort in ascending order we can simply call Collections.sort(list), but to sort in descending order we also need to pass the second parameter Collections.sort(list, Collections.reverseOrder());

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

public class Main {
   public static void main(String[] args) {

      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(430);
      list.add(220);
      list.add(112);
      list.add(677);
      list.add(439);
      list.add(905);
      System.out.println("Before Sorting : " + list);
      
      // sorting in ascending order
      Collections.sort(list);
      System.out.println("Sorting  in ascending order: " + list);
      
      // sorting in descending order
      Collections.sort(list, Collections.reverseOrder());
      System.out.println("Sorting  in descending order: " + list);
   }
}

Output:

Before Sorting : [430, 220, 112, 677, 439, 905]
Sorting in ascending order: [112, 220, 430, 439, 677, 905]
Sorting in descending order: [905, 677, 439, 430, 220, 112]

Java List Sort Lambda

Lambda expression is a new feature in Java that provides a concise way to represent a method. It is a short block of code that takes parameters and returns a value. Here, we sort an ArrayList by using lambda expression by defining two classes Employee and the main class.

class Employee {
   private int id;
   private String name;
   private int age;
   private long salary;

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

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public long getSalary() {
      return salary;
   }

   public void setSalary(long salary) {
      this.salary = salary;
   }

   @Override
   public String toString() {
      return "Employee [id=" + id + ", name=" + name 
           + ", age=" + age + ", salary=" + salary + "]";
   }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

   public static void main(String[] args) {

      List<Employee> employees = new ArrayList<Employee>();
      employees.add(new Employee(115, "William", 30, 385));
      employees.add(new Employee(110, "Amelia", 34, 400));
      employees.add(new Employee(100, "John", 22, 350));
      System.out.println("Before Sorting: " + employees);

      // sorting in ascending order by name
      Collections.sort(employees, 
                  (e1, e2) -> (e1.getName().compareTo(e2.getName())));
      System.out.println("Ascending order: " + employees);

      // sorting in descending order by name
      Collections.sort(employees, 
                  (e1, e2) -> (e2.getName().compareTo(e1.getName())));
      System.out.println("Descending order: " + employees);
   }

}

Output:

Before Sorting: [Employee [id=115, name=William, age=30, salary=385], Employee [id=110, name=Amelia, age=34, salary=400], Employee [id=100, name=John, age=22, salary=350]]

Ascending order: [Employee [id=110, name=Amelia, age=34, salary=400], Employee [id=100, name=John, age=22, salary=350], Employee [id=115, name=William, age=30, salary=385]]

Descending order: [Employee [id=115, name=William, age=30, salary=385], Employee [id=100, name=John, age=22, salary=350], Employee [id=110, name=Amelia, age=34, salary=400]]

In the above code, we have used the Lambda expression to sort the employees based on their name. Below code also produce the same result.

Collections.sort(employees, new Comparator<Employee>() {
   @Override
   public int compare(Employee e1, Employee e2) {
      return (int) (e1.getName().compareTo(e2.getName()));
   }
});
System.out.println("Ascending order: " + employees);

We can also use comparing method of the Comparator class.

Collections.sort(employees, Comparator.comparing(Employee::getName));
System.out.println("Ascending order: " + employees);

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.