Sort java.util.ArrayList

In this example we will learn how to sort a java.util.ArrayList using the Sort method of the Collection API. Lets now see how to do it.

Code Snippet

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListSortExample {

	public static void main(String args[]) 
	{
		//Creating new ArrayList object
                ArrayList<String> al = new ArrayList<String>();
		
                //Adding elements to the list
		al.add("Element1");
		al.add("Element3");
		al.add("Element2");
		al.add("Element4");
		
		System.out.println("******Before sorting******");
		for(String elements:al) 
			System.out.println(elements);
		}
		
		//Sort - Ascending Order
                Collections.sort(al);
		
		System.out.println("******After sorting******");
		for(String elements:al)
		{ 
			System.out.println(elements);
		}
	}
}

Output

******Before sorting******
Element1
Element3
Element2
Element4
******After sorting******
Element1
Element2
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *