How a list can be sorted in Java


A list can be sorted in ascending order using the java.util.Collections.sort() method. This method requires a single parameter i.e. the list to be sorted and no value is returned. The ClassCastException is thrown by the Collections.sort() method if there are mutually incomparable elements in the list.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      List aList = new ArrayList();
      aList.add("James");
      aList.add("Harry");
      aList.add("Susan");
      aList.add("Emma");
      aList.add("Peter");
      System.out.println("The unsorted ArrayList is: " + aList);
      Collections.sort(aList);
      System.out.println("The sorted ArrayList is: " + aList);
   }
}

The output of the above program is as follows −

The unsorted ArrayList is: [James, Harry, Susan, Emma, Peter]
The sorted ArrayList is: [Emma, Harry, James, Peter, Susan]

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The unsorted ArrayList is printed and then the ArrayList elements are sorted using Collections.sort(). Finally, the sorted ArrayList is printed. A code snippet which demonstrates this is as follows:

List aList = new ArrayList();
aList.add("James");
aList.add("Harry");
aList.add("Susan");
aList.add("Emma");
aList.add("Peter");
System.out.println("The unsorted ArrayList is: " + aList);
Collections.sort(aList);
System.out.println("The sorted ArrayList is: " + aList);

Updated on: 30-Jun-2020

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements