AdSense

AdSense3

Wednesday 16 September 2015

Sorting

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.   
  5. ArrayList<String> al=new ArrayList<String>();  
  6. al.add("Viru");  
  7. al.add("Saurav");  
  8. al.add("Mukesh");  
  9. al.add("Tahir");  
  10.   
  11. Collections.sort(al);  
  12. Iterator itr=al.iterator();  
  13. while(itr.hasNext()){  
  14. System.out.println(itr.next());  
  15.  }  
  16. }  
  17. }  
Output:Mukesh
       Saurav
       Tahir
       Viru
       

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.   
  5. ArrayList al=new ArrayList();  
  6. al.add(Integer.valueOf(201));  
  7. al.add(Integer.valueOf(101));  
  8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)  
  9.   
  10. Collections.sort(al);  
  11.   
  12. Iterator itr=al.iterator();  
  13. while(itr.hasNext()){  
  14. System.out.println(itr.next());  
  15.  }  
  16. }  
  17. }  
Output:101
       201
       230
              

No comments:

Post a Comment