最直接的方法是简单地让enum
自身实现Comparator
:
public enum SortBy implements Comparator<Item> {
CATEGORY {
@Override
public final int compare(final Item o1, final Item o2) {
return compareStrings(o1.getCategory(), o2.getCategory());
}
},
ENGLISH {
@Override
public final int compare(final Item o1, final Item o2) {
return compareStrings(o1.getEnglish(), o2.getEnglish());
}
},
NORWEGIAN {
@Override
public final int compare(final Item o1, final Item o2) {
return compareStrings(o1.getNorwegian(), o2.getNorwegian());
}
};
private static int compareStrings(final String s1, final String s2) {
if (s1 == null) {
return s2 == null ? 0 : -1;
}
if (s2 == null) {
return 1;
}
return s1.compareTo(s2);
}
}
无需进一步将每个枚举成员与比较器相关联,因为枚举成员是比较器。用法很简洁:
Collections.sort(items, SortBy.CATEGORY);
附录
在下面的评论中,您询问了常见的null
安全比较。我不确定第三方库可能会提供什么,但您可以很容易地自己实现它们。这是我们内部库之一中的两个:
static <T extends Comparable<? super T>> int compare(final T o1, final T o2) {
if (o1 == null) {
return o2 == null ? 0 : -1;
}
if (o2 == null) {
return 1;
}
return o1.compareTo(o2);
}
@SuppressWarnings("unchecked")
static int compare(final Object a, final Object b) {
if (a == b) {
return 0;
}
if (a == null) {
return -1;
}
if (b == null) {
return 1;
}
final Class<?> aClass = a.getClass();
final Class<?> bClass = b.getClass();
if (Comparable.class.isInstance(a) && aClass.isAssignableFrom(bClass)) {
return ((Comparable<Object>)a).compareTo(b);
}
if (Comparable.class.isInstance(b) && bClass.isAssignableFrom(aClass)) {
return ((Comparable<Object>)b).compareTo(a);
}
throw new IllegalArgumentException("Values must be comparable.");
}