Java Utility Library

Java Collections - sort() Method



The java.util.Collections.sort() method is used to sort the specified list according to the order induced by the specified comparator.

Syntax

public static <T> void sort(List<T> list, Comparator<? super T> c)

Here, T is the type of element in the list.


Parameters

list Specify the list to be sorted.
c Specify the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used.

Return Value

void type.

Exception

  • Throws ClassCastException, if the list contains elements that are not mutually comparable using the specified comparator.
  • Throws UnsupportedOperationException, if the specified list's list-iterator does not support the set operation.
  • Throws IllegalArgumentException, (optional) if the comparator is found to violate the Comparator contract.

Example:

In the example below, the java.util.Collections.sort() method is used to sort the given list using specified comparator.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object
    List<Integer> MyList = new ArrayList<Integer>();

    //populating the list
    MyList.add(15);
    MyList.add(20);
    MyList.add(-4);
    MyList.add(100);

    //printing the list
    System.out.println("MyList contains: " + MyList); 

    //creating a comparator for reverse order sorting
    Comparator<Integer> comp = Comparator.reverseOrder();

    //sorting the list
    Collections.sort(MyList, comp);

    //printing the list again
    System.out.println("MyList contains: " + MyList);   
  }
}

The output of the above code will be:

MyList contains: [15, 20, -4, 100]
MyList contains: [100, 20, 15, -4]

❮ Java.util - Collections