How to sort ArrayList in java

This Java Tutorial section we demonstrates how to use the sort() method in the Java ArrayList.

How to sort ArrayList in java

This Java Tutorial section we demonstrates how to use the sort() method in the Java ArrayList.

How to sort ArrayList in java

How to sort ArrayList in java

In this section you will learn how to sort ArrayList in java. ArrayList support dynamic array that can grow as needed. Array are of fixed length, after array are created they cannot grow or shrink. In this tutorial  we will sort the ArrayList using sort method of collection.  ArrayList does not have sort method so using sort method collection which sort the Arraylist. Now here is the code to sort the ArrayList in java.

import java.util.ArrayList;
import java.util.Collections;
public class Sort {
	public static void main(String args[])
	{
		System.out.println("Sorting of  Arraylist");
		ArrayList al= new ArrayList();
		al.add("Rose");
		al.add("India");
		al.add("Welcomes");
		al.add("You");
		System.out.println("Before Sort");
                System.out.println("*****************");	
                 for(String temp:al){
		System.out.println(temp);}
		System.out.println("*****************");	
                 System.out.println("After Sort");
                 System.out.println("*****************");	 
                                   Collections.sort(al);
 		 for(String temp1:al){
				System.out.println(temp1);
		}
	}
}

Description : In the above code we have taken a ArrayList  that can accept string and then adding the element to list and sorting by sort method of collection, lastly displaying the sorted arraylist to console using for each loop.

Output : When you will compile and execute code the output will be displayed as follows :

Download SourceCode