Wednesday, February 11, 2009

Java : Sorting ArrayList in Ascending and Descending order

Simple Program to sort Arraylist in Ascending and Descending order. U can also sort String,Float,Double.. etc in ArrayList.

ArrayList can be sorted using inbuilt java 1.5 class method Collections.sort(..).

Here is code, save it as file : Sorting.java


import java.util.*;

public class Sorting
{
public static void main(String[] args)
{
//Initilize ArrayList
ArrayList<Integer> arrayList = new ArrayList<Integer>();//also it can sort String,Float,Double.. etc

//creating Random numbers
//Random is a inbuilt java class in 1.5 in util package
Random random = new Random();

//putting Values
for(int i=1;i<=10;i++)
{
int temp = random.nextInt(100);//get random int values between 0 and 100
arrayList.add(temp);
}

//Sorting ArrayList
System.out.println("Before Sorting..");
System.out.println(arrayList);

Collections.sort(arrayList);//Sorting using sort method, default ascending sort

System.out.println("After Sorting Ascending..");
System.out.println(arrayList);

//useing Comparator to sort in descending order
Comparator<Integer> comparator = Collections.reverseOrder();
Collections.sort(arrayList,comparator);//Descending sorting using sort method

System.out.println("After Sorting Descending..");
System.out.println(arrayList);
}
}

No comments:

Post a Comment