Comparators in java

Comparator is a generic interface that has this declaration:

interface Comparator<T>

Here, specifies the type of objects being compared.

The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order:

int compare(T obj1, T obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. The method can throw a ClassCastException if the types of the objects are not compatible for comparison. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in reverse order, you can create a comparator that reverses the outcome of a comparison

Use a custom comparator

import java.util.*;

//A reverse comparator for strings.

class MyComp implements Comparator<String> {

public int compare(String a, String b) { String aStr, bStr;

aStr = a; bStr = b;

//Reverse the comparison. return bStr.compareTo(aStr);

}

// No need to override equals.

}

class CompDemo {

public static void main(String args[]) { // Create a tree set.

TreeSet<String> ts = new TreeSet<String>(new MyComp());

//Add elements to the tree set. ts.add("C");

ts.add("A");

ts.add("B");

ts.add("E");

ts.add("F");

ts.add("D");
//Display the elements. for(String element : ts)

System.out.print(element + " ");

System.out.println();

}

}

F E D C B A

Leave a Comment