Java Utility Library

Java Collections - sort() Method



The java.util.Collections.sort() method is used to sort the specified list into ascending order, according to the natural ordering of its elements.

Syntax

public static <T extends Comparable<? super T>> void sort(List<T> list)

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


Parameters

list Specify the list to be sorted.

Return Value

void type.

Exception

  • Throws ClassCastException, if the list contains elements that are not mutually comparable (for example, strings and integers).
  • Throws UnsupportedOperationException, if the specified list's list-iterator does not support the set operation.
  • Throws IllegalArgumentException, (optional) if the implementation detects that the natural ordering of the list elements is found to violate the Comparable contract.

Example:

In the example below, the java.util.Collections.sort() method is used to sort the given list in ascending order.

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); 

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

    //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: [-4, 15, 20, 100]

❮ Java.util - Collections