Java Collections sort()

In this guide, you will learn about the Collections sort() method in Java programming and how to use it with an example.

1. Collections sort() Method Overview

Definition:

The sort() method of the Collections class in Java is used to sort the elements of a list on the basis of their natural ordering or based on a provided comparator.

Syntax:

1. Collections.sort(List<T> list) 
2. Collections.sort(List<T> list, Comparator<? super T> c)

Parameters:

1. list: The list to be sorted.

2. c: The comparator to determine the order of the list.

Key Points:

- For the first syntax, all elements in the list should implement the Comparable interface, and they should be mutually comparable.

- For the second syntax, a custom ordering can be implemented using the provided comparator.

- The sorting algorithm is a modified mergesort (in older versions of Java) or Timsort (in more recent versions).

- This operation is stable, meaning that the order of equal elements will remain unchanged.

- It throws ClassCastException if elements in the list are not mutually comparable.

- It throws UnsupportedOperationException if the provided list's list-iterator doesn't support the set operation.

2. Collections sort() Method Example


import java.util.*;

public class CollectionsSortExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));

        // Sorting in natural order
        Collections.sort(fruits);
        System.out.println("Sorted in natural order: " + fruits);

        // Sorting in reverse order using a comparator
        Collections.sort(fruits, Comparator.reverseOrder());
        System.out.println("Sorted in reverse order: " + fruits);
    }
}

Output:

Sorted in natural order: [apple, banana, cherry]
Sorted in reverse order: [cherry, banana, apple]

Explanation:

In the provided example, we first sort the list of fruits in their natural order. Since the elements are strings, their natural order is lexicographical. After that, we use a comparator to sort them in reverse order and print the result.

Comments