Home Java Beginners How to sort ArrayList in java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

How to sort ArrayList in java

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

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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 11, 2013

Related Tutorials

Ask Questions?    Discuss: How to sort ArrayList in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com