Sort Elements in an ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

In order to sort elements in an ArrayList in Java, we use the Collections.sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order.

Declaration −The java.util.Collections.sort() method is declared as follows −

public static void sort(List list)

where list is an object on which sorting needs to be performed.

Let us see a program to sort elements in an ArrayList in Java −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<String> zoo = new ArrayList<String>();
      zoo.add("Zebra");
      zoo.add("Lion");
      zoo.add("Tiger");
      Collections.sort(zoo);
      System.out.println("The list after sorting is : " + zoo);
   }
}

Output

The list after sorting is : [Lion, Tiger, Zebra]
raja
Published on 08-Jan-2019 12:51:10
Advertisements