how to use a comparator interface in a TreeSet using the collections in java
Previous | Home | Next |
In this example we shall see how can we use the comparator interface on a TreeSet for controlling the ordering the elements of a TreeSet.
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 compare(Obejct obj1, Object obj2) method of the Comparable Interface, which returns the negative ,0 , positive values if the obj1 comes befor the obj2 in the ordering , obj1 and obj2 hold same place in the order, if obj1 comes after the obj2 in the ordering respectively in a TreeSet. The syntax of a compare() method is given as:
public int compare(Obect obj1, Object obj2)
this method returns
negative value->obj1 comes befor the obj2
positive value->obj1 comes after the obj2 in the ordering
zero value-> of obj1 and obj2 are ordered at the same position
In this example we have created a TreeSet in which we are adding the elements which are ordered in it by the definition provided by the comparator. For creating a comparator in the given we have created an anonymous class which reverses the order in which objects are added to the TreeSet.
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)
{
return -1; /* here we are placing the first object first in the tree set*/
/* i.e. we are reversing the order in the which objects are added to the TreeSet*/
}
});
ts.add(2); // adding the objects to the TreeSet ts
ts.add(4);
ts.add(7);
ts.add(8);
ts.add(1);
ts.add(9);
System.out.println(ts); // displaying the objects contained in the list
}
}
The output of the above written code is as follows:
The objects of the tree set are as follows:
[9, 1, 8, 7, 4, 2]
As you can see that the objects in the TreeSet are added reversely as we intended using the comparator.
Previous | Home | Next |