guava - Java comparator by using priority for classes that extend a common parent class -
i need implement several comparators in java.
i have lot of known classes, a1
, a2
, a3
, ..., an
, extends class a
. want to comparator class based on guava ordering
, following:
ordering<a> sortertype1 = new ordering<a>() { // here, provide set or similar keeps in memory // class types , associated priority. @override public int compare(a left, right) { // return -1 if class of left has higher priority wrt class of right; // return 0 if class of left has same priority wrt class of right; // return 1, otherwise. }
since need develop lot of different comparators, don't want put priority inside class type, since there several priorities differentiated each comparator. i'm missing parts comments.
what effective , efficient implementation of parts comments?
don't write compare implementation yourself, use ordering
super powers (ordering#explicit(list)
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(); } }); system.out.println(explicitbyclassordering.sortedcopy( immutablelist.of(new a3(), new a2(), new a3(), new a1(), new a4()))); // [test$a1, test$a4, test$a3, test$a3, test$a2]