Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sorting using Collection

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 288
    Comment on it

    To sort the collection elements Collection class gives us the methods. In case of Set collection, we have TreeSet that can use to set the Set elements. We can sort elements of type String objects, Wrapper class objects and User-defined class objects.

    Method that use for sorting

    public void sort(List myList) 
    Example:

    ArrayListmyList=new ArrayList(); 
    myList.add("John");
    myList.add("Adam");
    myList.add("Smith");
    myList.add("Mike");

    Collections.sort(myList);
    Iterator iterator= myList.iterator();
    while(iterator.hasNext()){
    System.out.println(iterator.next());
    }

    O/P: Adam John Mike Smith

    Another Example

    ArrayList myList =new ArrayList(); 
    myList.add(Integer.valueOf(1005));
    myList.add(Integer.valueOf(1002));
    al.add(1003);
    Collections.sort(myList);

    Iterator iterator = myList.iterator();
    while(iterator.hasNext()){
    System.out.println(iterator.next());
    }
    }
    }
    O/P: 1002 1003 1005

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: