Advertisement
int compare(T obj1, T obj2)
import java.util.*;
class Comp implements Comparator<Integer>
{
public int compare(Integer obj1, Integer obj2) //Implementing Comparator's compare() method to give a descending ordering
{
return(obj2.compareTo(obj1)); //Integer's compareTo() method compares two Integer objects
}
public static void main(String... ar)
{
TreeSet<Integer> pq= new TreeSet<Integer>(new Comp()); //Passing an object of implementer of Comparator Interface
pq.add(17);
pq.add(40);
pq.add(72);
pq.add(39);
pq.add(234);
pq.add(24);
pq.add(22);
System.out.println("TreeSet with descending ordering" + pq);
System.out.println("Size of TreeSet = "+ pq.size());
}
}
TreeSet with descending ordering : 234 72 40 39 24 22 17
Size of TreeSet = 7
Advertisement
import java.util.*;
class Comp implements Comparator
{
public int compare(String obj1, String obj2) //overriding Comparator's compare() method to give a descending ordering
{
return(obj2.compareTo(obj1)); //String's compareTo() method compares two String objects.
}
public static void main(String... ar)
{
TreeSet<String> tree= new TreeSet<String>(new Comp2()); //passing an object of implementer of Comparator Interface
tree.add("H");
tree.add("E");
tree.add("M");
tree.add("A");
tree.add("N");
System.out.println("Content of TreeSet with descending ordering" + tree);
System.out.println("Size of TreeSet = "+ tree.size());
}
}
Content of TreeSet with descending ordering[N, M, H, E, A]
Size of TreeSet = 5
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement