Tuesday 6 December 2016

How to sort an ArrayList in java with it's example

ArrayList’s elements are display according to the sequence it is put inside. The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Example:
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4. public class DemoSortArrayList{
  5. public static void main(String args[]){
  6. List<String> unsortList = new ArrayList<String>();
  7. unsortList.add("CCC");
  8. unsortList.add("111");
  9. unsortList.add("AAA");
  10. unsortList.add("BBB");
  11. unsortList.add("ccc");
  12. unsortList.add("bbb");
  13. unsortList.add("aaa");
  14. unsortList.add("333");
  15. unsortList.add("222");
  16. //before sort the source now
  17. System.out.println("ArrayList is unsort");
  18. for(String temp: unsortList){
  19. System.out.println(temp);
  20. }
  21. //sort the list now
  22. Collections.sort(unsortList);
  23. //after sorted now
  24. System.out.println("ArrayList is sorted");
  25. for(String temp: unsortList){
  26. System.out.println(temp);
  27. }
  28. }
  29. }
Output:
ArrayList is unsort
CCC
111
AAA
BBB
ccc
bbb
aaa
333
222
ArrayList is sorted
111
222
333
AAA
BBB
CCC
aaa
bbb
ccc

No comments:

Post a Comment