Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages


We can sort the elements of:

  1. String objects
  2. Wrapper class objects
  3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection elements are of Set type, we can use TreeSet.But We cannot sort the elements of List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects

  1. import java.util.*;
  2. class TestSort1{
  3. public static void main(String args[]){
  4. ArrayList<String> al=new ArrayList<String>();
  5. al.add(“Viru”);
  6. al.add(“Saurav”);
  7. al.add(“Mukesh”);
  8. al.add(“Tahir”);
  9. Collections.sort(al);
  10. Iterator itr=al.iterator();
  11. while(itr.hasNext()){
  12. System.out.println(;
  13.  }
  14. }
  15. }

Test it Now


Example of Sorting the elements of List that contains Wrapper class objects

  1. import java.util.*;
  2. class TestSort2{
  3. public static void main(String args[]){
  4. ArrayList al=new ArrayList();
  5. al.add(Integer.valueOf(201));
  6. al.add(Integer.valueOf(101));
  7. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
  8. Collections.sort(al);
  9. Iterator itr=al.iterator();
  10. while(itr.hasNext()){
  11. System.out.println(;
  12.  }
  13. }
  14. }