mat_boy mat_boy - 6 months ago 27
Java Question

Java comparator by using priority for classes that extend a common parent class

I need to implement several comparators in Java.

I have a lot of known classes,

, ...,
, which all extends class
. What I want to to is a comparator class based on Guava
, like the following:

Ordering<A> sorterType1 = new Ordering<A>() {
// Here, provide a Set or something similar that keeps in memory
// the class types and the associated priority.

public int compare(A left, A right) {
// return -1 if class of left has an higher priority wrt class of right;
// return 0 if class of left has the same priority wrt class of right;
// return 1, otherwise.

Since I need to develop a lot of different comparators, I don't want to put the priority inside the class type, since there are several priorities differentiated for each comparator.
What I'm missing are the parts with comments.

What is the most effective and efficient implementation of the parts with comments?


Don't write compare implementation by yourself, use Ordering super powers (Ordering#explicit(List) to be exact):

List<Class<? extends A>> myOrder = ImmutableList.of(
    A1.class, A4.class, A3.class, A2.class);
Ordering<A> explicitByClassOrdering = Ordering.explicit(myOrder)
    .onResultOf(new Function<A, Class<? extends A>>() {
      @Override public Class<? extends A> apply(A a) {
        return a.getClass();

    ImmutableList.of(new A3(), new A2(), new A3(), new A1(), new A4())));
// [Test$A1, Test$A4, Test$A3, Test$A3, Test$A2]