How to sort an ArrayList in Ascending Order in Java

Given an unsorted ArrayList, the task is to sort this ArrayList in ascending order in Java.

Examples:

Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Output: Sorted ArrayList: [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]

Input: Unsorted ArrayList: [Geeks, For, ForGeeks]
Output: Sorted ArrayList: [For, ForGeeks, Geeks]



Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

Syntax:

Collections.sort(ArrayList);

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// How to sort ArrayList in ascending order
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Get the ArrayList
        ArrayList<String>
            list = new ArrayList<String>();
  
        // Populate the ArrayList
        list.add("Geeks");
        list.add("For");
        list.add("ForGeeks");
        list.add("GeeksForGeeks");
        list.add("A computer portal");
  
        // Print the unsorted ArrayList
        System.out.println("Unsorted ArrayList: "
                           + list);
  
        // Sorting ArrayList in ascending Order
        // using Collection.sort() method
        Collections.sort(list);
  
        // Print the sorted ArrayList
        System.out.println("Sorted ArrayList "
                           + "in Ascending order : "
                           + list);
    }
}

chevron_right


Output:

Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Sorted ArrayList in Ascending order : [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]


My Personal Notes arrow_drop_up

Technical Content Engineer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.