Collections.sort() in Java with Examples


The collection class is an enhanced static method to sort the elements from a particular collection of a list or an array. For this process, we can use a tree set also, when we operate on a set of elements as present as the raw set type primarily. The Collections.sort() method is present in the java.util.Collections class, and enables the user to sort the elements from a specific list in an ascending order. The method is an upgraded version of the java.util.Arrays.sort() method class, which is capable to sort the elements from a linked list as well as queue and many more. In one word, the collection class are capable to sort the elements from a list in an effective manner. Let’s take an example −

We are going to use , <public static void sort(List myList)>

Possible myList for the process > It is a List type (any), from where we want to sort the objects.

Unfortunately, this method will not return anything as output

For Example

Let us suppose that our list contains

{"TutorialsPoint", "Friends", "Dear", "Is", "The", "Best", “Hey”}

After using Collection.sort(), we obtain a sorted list as

{“Hey”, "Dear", "Friends", "TutorialsPoint", "Is", "The", "Best"}

There are some certain ways to sort the elements from a collection list. By using the method we can collect the data from a sring object, wrapper class or a user defined class.

  • public void sort(List list) − This notation can be used to sort the elements from a list. The only codition is, the present elements must be the comparable tye in nature. Here we can the string class and a wrapper class to implement the process. To store the value of an object present in a string and wrapper class, it must be comparable in nature.

  • sort(List list, Comparator c) − This method sorts the elements of the particular list according to the order by a comparator class as delared.

Algorithm to use the Collections.sort() Method

In this possible algorithm, we are going to show you how to apply a Collections.sort() method in a Java environment. With this algorithm, we will try to build some syntax and some Java codes to explain the problem statement further.

  • Step 1 − Start the process.

  • Step 2 − Import and declare the usable Java packages.

  • Step 3 − Declare a public class.

  • Step 4 − Construct a string argument.

  • Step 5 − Create a string list.

  • Step 6 − Populate the list by adding some data elements into it.

  • Step 7 − Declare the Collections.sort method to filter the elements of an array list as per the process.

  • Step 8 − Run the process.

  • Step 9 − Print the data elements from the sorted list.

  • Step 10 − Get the result and terminate the process.

Syntax to Implement the Collections.sort() Method

Fruit(int id, String name, String taste){
   this.id=id;
   this.name=name;
   this.taste=taste;
}
@Override //Override the method
public int compareTo(Object o) {
   Fruit f = (Fruit) o;
   return this.id - f.id ;
}
}
//Sorting Method 1
Collections.sort(fruitList);
fruitList.forEach(fruit -> {
   System.out.println(fruit.getId() + " " + fruit.getName() + " " +
   fruit.getTaste());
});
//Sorting Method 2
Collections.sort(fruitList, (a, b) -> {
   return a.getName().compareTo(b.getName());
});
//Sorting by using a wrapper class{
ArrayList al=new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
   System.out.println(itr.next());
}

In this syntax mentioned above, we have tried to show you the construction process of the Collection.sort() method in two different ways. By using them, we are heading towards the possible approaches to explain the given statement by applying various Java methods.

Approaches to Follow

  • Approach 1 − Java program to explain the working of a Collections.sort() method

  • Approach 2 − Java program to illustrate the working method of a Comparator interface and the Collections.sort() to sort according to the user defined criteria

Approach 1: Demonstrate the Working of Collections.sort()

In this possible approach, we are going to show you to sort an Array List in an ascending manner. For this process −

  • Time Complexity − denoted as O(N log N), where the base time complexity for the process is O(nlog(n)).

  • Auxiliary Space − The auxiliary space denoted as the O(1).

Example 1

//Java program to explain the working of a Collections.sort() method
import java.util.*;
public class Collectionsorting0710{
   public static void main(String[] args){
      ArrayList<String> al = new ArrayList<String>();
      al.add("I");
      al.add("AM");
      al.add("GOING");
      al.add("TO");
      al.add("DHAKA");
      Collections.sort(al);
      System.out.println("Here is the list after the use of the" +
      " Collection.sort() method:\n" + al);
   }
}

Output

Here is the list after the use of the Collection.sort() method:
[AM, DHAKA, GOING, I, TO]

Here in this particular approach, we are going to operate a string class to mold an another array list from it.The time complexity has been denoted as O(N log N), where the base time complexity for the process is O(nlog(n)).And the auxiliary Space : The auxiliary space denoted as the O(1).

Example 2

//Java program to explain the working of the Collections.sort() to a descending order.
import java.util.*;
public class Collectionsorting{
   public static void main(String[] args){
      ArrayList<String> al = new ArrayList<String>();
      al.add("I");
      al.add("AM");
      al.add("GOING");
      al.add("BY");
      al.add("MAITREE EXPRESS");
      Collections.sort(al, Collections.reverseOrder());
      System.out.println("Possible list after the use of the" +
      " Collection.sort() method:\n" + al);
   }
}

Output

Possible list after the use of the Collection.sort() method:
[MAITREE EXPRESS, I, GOING, BY, AM]

Approach 2: Sorting Operation With Comparator Interface and Collections.sort()

Now we are going to explain some user specific process to demonstrate the process of sorting with an array list.

  • In the example number 3, we will use a comparator interface.

  • For the example number 3A, we will show you the difference between Arrays.sort() and the Collections.sort().

  • At last, for the 3B; we will show you the time complexity for the Arrays.sort() and Collections.sort().

Example 1

//Java program to illustrate the working method of a Comparator interface and the Collections.sort() to sort according to the user defined criteria.
import java.util.*;
import java.lang.*;
import java.io.*;
class Student{
   int rollno;
   String name, address;
   public Student(int rollno, String name,
   String address){
      this.rollno = rollno;
      this.name = name;
      this.address = address;
   }
   public String toString(){
      return this.rollno + " " + this.name +
      " " + this.address;
   }
}
class Sortbyroll implements Comparator<Student>{
   public int compare(Student a, Student b){
      return a.rollno - b.rollno;
   }
}
public class Main{
   public static void main (String[] args){
      ArrayList<Student> ar = new ArrayList<Student>();
      ar.add(new Student(07, "ARB - 0710", "BAD BRINBACH"));
      ar.add(new Student(16, "RDD - 1610", "ROTTAL INN"));
      ar.add(new Student(2022, "REBA - 2001", "EU CAMPUS"));
      System.out.println("Unsorted Data Elements Present In The List");
      for (int i=0; i<ar.size(); i++)
      System.out.println(ar.get(i));
      Collections.sort(ar, new Sortbyroll());
      System.out.println("\nSorted elements by the Roll Number");
      for (int i=0; i<ar.size(); i++)
      System.out.println(ar.get(i));
   }
}

Output

Unsorted Data Elements Present In The List
7 ARB - 0710 BAD BRINBACH
16 RDD - 1610 ROTTAL INN
2022 REBA - 2001 EU CAMPUS
Sorted elements by the Roll Number
7 ARB - 0710 BAD BRINBACH
16 RDD - 1610 ROTTAL INN
2022 REBA - 2001 EU CAMPUS

Example 2

import java.util.*;
public class Collectionsort0710{
   public static void main(String[] args){
      String domains[] = {"I", "WILL REACH",
      "BY", "AFTERNOON"};
      List colList =
      new ArrayList(Arrays.asList(domains));
      Collections.sort(colList);
      System.out.println("The list after the use of the" +
      "method of Collection.sort() :\n" +
      colList);
   }
}

Output

Note: Collectionsort0710.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The list after the use of themethod of Collection.sort() :
[AFTERNOON, BY, I, WILL REACH]

Example 3

import java.io.*;
import java.util.*;
public class ARBRDD100520220101 {
   public static void main (String[] args) {
      int len = 5000000;
      int[] arr = new int[len];
      for (int i = len; i > 0; i--)
      arr[len - i] = i;
      ArrayList<Integer> list = new ArrayList<>();
      for (int i = len; i > 0; i--)
      list.add(i);
      long startA = System.currentTimeMillis();
      Arrays.sort(arr);
      long stopA = System.currentTimeMillis();
      long startAL = System.currentTimeMillis();
      Collections.sort(list);
      long stopAL = System.currentTimeMillis();
      System.out.println("Time taken by the process of Arrays.sort(): " +
      (stopA - startA));
      System.out.println("Time taken by the process of Collections.sort() is: " + (stopAL - startAL));
   }
}

Output

Time taken by the process of Arrays.sort() is: 15
Time taken by the process of Collections.sort() is: 31

Conclusion

The Collection.sort process performs the process of sorting in the ascending order. By using this method, we can perform the reverseOrder() operation which returns a comparator class. On the other hand, reverseOrder(Comparator cmp) method gives us a return comparator which will be the reverse value of that specific comparator class. In this article today, we have learned about the sorting process of a collection class. By using the above mentioned algorithm, syntax and Java codes we have solved the problem statement in an efficient manner.

Updated on: 27-Dec-2023

31 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements