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)