how to sort the elements of a TreeSet using the Comparator interface of the collections in java
Previous | Home | Next |
In this example we shall see how to sort the elements of a TreeSet using the Comparator class in the collections.
For creating a TreeSet we have to import the java.util package in which we have the class java.util.TreeSet which contains the definition and various that can be performed on a TreeSet. In this example we have created a class named CollectionExample in which we have created a TreeSet and added some elements to it.
In this example we have used the compareTo(Object obj) method of the Comparable Interface. The syntax for this method is,
public int compareTo(Object obj)
The method compares the current instance with an element passed in as an argument. If the current instance comes before the argument in the ordering, a negative value is returned. If the current instance comes after, then a positive value is returned. Otherwise, zero is returned. It is not a requirement that a zero return value signifies equality of elements. A zero return value just signifies that two objects are ordered at the same position.
In this example we have created a TreeSet and add the elements to it. The elements are placed according to the ordering by the TreeSet's comparator. For using a comparator we have created an anonymous class in which we have defined the functionality of the comparator. In this example we have create a comparator which places the elements of the TreeSet in ascending order.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
// in the below TreeSet Constructor we are passing the comparator object, by creating an anonymous class
TreeSet<Integer> ts=new TreeSet<Integer>(new Comparator<Integer>(){
public int compare(Integer num1, Integer num2) // implementing the compare(obj,obj)method of Comparator interface
{
Integer inum1, inum2;
inum1=num1;
inum2=num2;
if(inum1.compareTo(inum2)<1) // comparing the values for sorting by using the compareTo(obj) method of Comparable interface
{
return -1; // returning the first object
}
else
{
return 1;
}
}
});
ts.add(2);
ts.add(4);
ts.add(7);
ts.add(8);
ts.add(1);
ts.add(9);
System.out.println("The objects of the tree set are as follows: ");
System.out.println(ts);
}
The output of the above code will be displayed as:
The objects of the tree set are as follows:
[1, 2, 4, 7, 8, 9]
You can see the output gives us the objects of the TreeSet in the ascending order, just as we wanted through our comparator.
Previous | Home | Next |