Thursday, August 16, 2012How to sort ArrayList in java - List Sorting - Ascending Descending Order

Sorting ArrayList in Java is not difficult, by using Collections.sort() method you cansort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored inArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.

Sorting ArrayList in Java – Code Example

ArrayList Sorting Example in Java - Ascending Descending Order Code
Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have usedComparable method of String for sorting String on there natural order, You can also useComparator in place of Comparable to sort String on any other order than natural ordering e.g. in reverse order by using Collections.reverseOrder() or in case insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.

importjava.util.ArrayList;
import java.util.Collections;
/**
*
* Java program to demonstrate How to sort ArrayList in Java in both ascending
* and descending order by using core Java libraries.
*
* @author Javin
*/

public class CollectionTest{


public staticvoid main(String args[]){

//Creating and populating ArrayList in Java for Sorting
ArrayList<String> unsortedList =new ArrayList<String>();

unsortedList.add("Java");
unsortedList.add("C++");
unsortedList.add("J2EE");

System.err.println("unsorted ArrayList in Java : " + unsortedList);

//Sorting ArrayList in ascending Order in Java
Collections.sort(unsortedList);
System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);

//Sorting ArrayList in descending order in Java
Collections.sort(unsortedList,Collections.reverseOrder());
System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
}
}
Output:
unsorted ArrayList in Java : [Java, C++, J2EE]
Sorted ArrayList in Java - Ascending order : [C++, J2EE, Java]
Sorted ArrayList in Java - Descending order : [Java, J2EE, C++]

That's all on How to Sort ArrayList in Java on both ascending and descending order. Just remember that Collections.sort() will sort the ArrayList in ascending order and if you provide reverse comparator it will sort the ArrayList in descending order in Java.


Other Java Collection tutorials:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章