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:
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<String>
list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "For" );
list.add( "ForGeeks" );
list.add( "GeeksForGeeks" );
list.add( "A computer portal" );
System.out.println( "Unsorted ArrayList: "
+ list);
Collections.sort(list);
System.out.println( "Sorted ArrayList "
+ "in Ascending order : "
+ list);
}
}
|
Output:
Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Sorted ArrayList in Ascending order : [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks]
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Apr, 2023
Like Article
Save Article