Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a natural comparator exist in the standard api?

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.

like image 246
Yishai Avatar asked Jul 13 '10 20:07

Yishai


People also ask

Which one of these classes have Comparator method?

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).

When would you use a Comparator instead of implementing comparable?

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.

Where is Comparator and comparable used?

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.


1 Answers

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)); 
like image 87
Julien Avatar answered Sep 30 '22 21:09

Julien