Java Utility Library

Java ArrayList - sort() Method



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

Syntax

public void sort(Comparator<? super E> c)

Here, E is the type of element maintained by the container.


Parameters

c Specify the comparator used to compare list elements. If null, element's natural ordering is used.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.ArrayList.sort() method is used to sort the given list.

import java.util.*;

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

    //populating the ArrayList
    MyList.add(50);
    MyList.add(40);
    MyList.add(10);
    MyList.add(30);
    MyList.add(20);

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

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

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

The output of the above code will be:

MyList contains: [50, 40, 10, 30, 20]
MyList contains: [10, 20, 30, 40, 50]

❮ Java.util - ArrayList