I need a comparator as part of a strategy pattern that can either use the natural ordering of the objects or some custom ordering. For the natural ordering case, I wrote a simple comparator:
private static class NaturalComparator<T extends Comparable<? super T>> implements Comparator<T> { @Override public int compare(T o1, T o2) { return o1.compareTo(o2); } }
Seems simple enough, but I was wondering if anyone knew of one in the standard API. I looked at TreeMap, and it does it without such a class, so when that code was written, the apparent answer would be no, but perhaps it was added later.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element).
To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.
Comparable should be used when you compare instances of the same class. Comparator can be used to compare instances of different classes. Comparable is implemented by the class which needs to define a natural ordering for its objects. For example, String implements Comparable.
Added to Comparator in Java 8:
static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
Use it like this, for example:
Comparator<Double> natural = Comparator.<Double>naturalOrder(); return natural.compare(1.0, 1.1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With