Sorting in Collection
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 a
collection. If collection elements are of a Set type, we can use TreeSet. However,
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 the Comparable type.
Example to sort string objects
import java.util.*;
class TestSort1{
public static void main(String args[]){
ArrayList<String> a=new ArrayList<String>();
a.add("Apple");
a.add("Grapes");
a.add("carrot");
a.add("Banana");
Collections.sort(a);
Iterator itr=a.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Example to sort string objects in reverse order
import java.util.*;
class TestSort2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Apple");
al.add("Grapes");
al.add("Carrot");
al.add("Banana");
Collections.sort(al,Collections.reverseOrder());
Iterator i=al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Example to sort Wrapper class objects
import java.util.*;
class TestSort3{
public static void main(String args[]){
ArrayList x=new ArrayList();
x.add(Integer.valueOf(201));
x.add(Integer.valueOf(101));
x.add(Integer.valueOf(301));
Collections.sort(x);
Iterator itr=x.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Example to sort user-defined class objects
import java.util.*;
class Student implements Comparable<Student> {
public String name;
public Student(String name) {
this.name = name;
}
public int compareTo(Student person) {
return name.compareTo(person.name);
}
}
public class TestSort4 {
public static void main(String[] args) {
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student("Seetha"));
al.add(new Student("Sarayu"));
al.add(new Student("Janaki"));
al.add(new Student("Veda"));
Collections.sort(al);
for (Student s : al) {
System.out.println(s.name);
}
}
}