Collections.sort() in Java

 The Java programming language offers a useful method called java.util.Collections.sort() to sort the elements of a collection in ascending order. The Collections.sort() method is present in the java.util.Collections class and is similar to the java.util.Arrays.sort() method. However, it is more versatile than the Arrays.sort() method as it can sort the elements of various data structures that implement the List interface, such as an ArrayList, LinkedList, AbstractList, Queue, and more.

Let us take a look at some examples to understand how the Collections.sort() method works and how it can be used to sort a collection. We will also explore how to implement Comparable and Comparator interfaces to customize the sorting behavior.

Example 1: Sorting and reversing a list of integers In this example, we will create a list of integers and sort them in natural order (ascending) using the Collections.sort() method. We will then sort the list in reverse order (descending) using the Collections.reverseOrder() method. Here is the code:

java
import java.util.*; public class CollectionSorting { public static void main(String[] args) { // Create a list of integers List<Integer> list = new ArrayList<>(); list.add(10); list.add(5); list.add(20); // Sort the list in natural order Collections.sort(list); // Displaying the sorted list System.out.println(list); // Sort the list in reverse order Collections.sort(list, Collections.reverseOrder()); // Displaying the sorted list System.out.println(list); } }

In the above example, we first create an ArrayList of integers and add some values to it. Then, we sort the list using the Collections.sort() method. After that, we display the sorted list using the System.out.println() method. Finally, we sort the list in reverse order using the Collections.reverseOrder() method and display the sorted list again.

The output of the above code will be:

csharp
[5, 10, 20] [20, 10, 5]

Note that the Collections.reverseOrder() method returns a comparator that can be used to reverse the sorting order of a collection.

Example 2: Sorting a list of user-defined objects using Comparable interface In this example, we will create a user-defined class called Point that implements the Comparable interface. The Point class has two variables: x and y, representing the coordinates of a point. We will sort a list of Point objects based on their x-coordinate. Here is the code:

java
import java.util.*; class Point implements Comparable<Point> { int x, y; Point(int x, int y) { this.x = x; this.y = y; } public int compareTo(Point p) { return this.x - p.x; } } public class CollectionSorting { public static void main(String[] args) { // Create a list of Point objects List<Point> list = new ArrayList<>(); list.add(new Point(5, 10)); list.add(new Point(2, 20)); list.add(new Point(10, 30)); // Sort the list in natural order Collections.sort(list); // Display the sorted points for (Point p : list) System.out.println(p.x + " " + p.y); } }

In the above example, we first create a Point class that implements the Comparable interface. We override the compareTo() method to compare two Point objects based on their x-coordinate. Then, we create an ArrayList of Point objects and add some points to it. We sort the list using the Collections.sort() method. Finally, we display the sorted list of points using a for loop.

Example 2 Output: 2 20 5 10 10 30

In Example 2, we have created a class named "Point" which implements the "Comparable" interface. The "Comparable" interface provides a way to define the natural order of the objects of a class. In this example, we have defined the natural order of the "Point" objects based on their x-coordinates. The "compareTo()" method compares the x-coordinates of two "Point" objects and returns a negative integer, zero, or a positive integer as the first object is less than, equal to, or greater than the second object, respectively.

In the main method, we have created a list of "Point" objects and added three points to it. Then, we have used the "Collections.sort()" method to sort the list in the natural order defined by the "compareTo()" method. Finally, we have displayed the sorted list of points using a for loop.

Example 3: Using a class implementing Comparator interface, to sort the passed list of points according to x-coordinates.

// Java program to demonstrate // working of Collections.sort() import java.util.; import java.lang.; import java.io.*;

// Point class which does not implement // Comparable interface. Thus the objects // of this class are not comparable. class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } }

// This class implements // Comparator interface class MyCmp implements Comparator<Point> { // Sorts the Point objects according // to x-coordinates in natural order public int compare(Point p1, Point p2) { return p1.x - p2.x; } }

// Main Class class GfG { public static void main(String[] args) { // Create a list of Integers List<Point> list = new ArrayList<Point>(); list.add(new Point(5, 10)); list.add(new Point(2, 20));
list.add(new Point(10, 30));

java
// List is sorted in natural order // Passing the list and MyCmp object Collections.sort(list, new MyCmp()); // Displaying the points for (Point p: list) System.out.println(p.x + " " + p.y); }

} Output: 2 20 5 10 10 30

In Example 3, we have created a class named "MyCmp" which implements the "Comparator" interface. The "Comparator" interface provides a way to define the custom order of the objects of a class. In this example, we have defined the custom order of the "Point" objects based on their x-coordinates. The "compare()" method compares the x-coordinates of two "Point" objects and returns a negative integer, zero, or a positive integer as the first object is less than, equal to, or greater than the second object, respectively.

In the main method, we have created a list of "Point" objects and added three points to it. Then, we have used the "Collections.sort()" method to sort the list using the "MyCmp" object, which defines the custom order of the "Point" objects. Finally, we have displayed the sorted list of points using a for loop.

Arrays.sort() vs Collections.sort()

The "Arrays.sort()" and "Collections.sort()" methods are used to sort arrays and collections, respectively. The main difference between the two methods is that "Arrays.sort()" works only for arrays, whereas "Collections.sort()" can work with any Collection object, including Lists, Sets, and Queues.

Another important difference between the two methods is that "Arrays.sort()" uses a quicksort algorithm for sorting, which is an efficient sorting algorithm for large arrays. On the other hand, "Collections.sort()" uses a mergesort algorithm for sorting, which is an efficient algorithm for sorting linked lists and other non-random access data structures.

In terms of performance, "Arrays.sort()" is generally faster than "Collections.sort()" for sorting large arrays because quicksort has a lower overhead than mergesort. However, for small data sets, the performance difference between the two methods is negligible.

It is important to note that both "Arrays.sort()" and "Collections.sort()" sort the elements in ascending order by default. However, they also provide a way to sort the elements in descending order by passing a Comparator object that defines the sorting order.

In conclusion, both "Arrays.sort()" and "Collections.sort()" are powerful sorting methods in Java. "Arrays.sort()" is preferred for sorting large arrays, while "Collections.sort()" is preferred for sorting collections of objects. Both methods provide an efficient way to sort elements in ascending or descending order.

Previous Post Next Post