我正在开发以下小实用程序类:
public class Collections2 {
public static <T, K extends Comparable<? super K>> Comparator<T>
comparatorBy(Function<T, K> selector) {
return (a, b) -> selector.apply(a).compareTo(selector.apply(b));
}
public static <T, K extends Comparable<? super K>> void
sortBy(List<T> list, Function<? super T, K> selector) {
Collections.sort(list, comparatorBy(selector));
}
}
这允许按python style key functions排序,所以我不必为我想要排序的每个字段编写完整的比较器,而是我可以写:
List<Person> persons = ...;
Collections2.sortBy(persons, Person::getName);
这很好,我想用这种风格编写了很多实用方法,如minBy
,maxBy
,groupBy
等等。
但是如果有人想要使用这些新的实用功能并进行比较呢?我想到了以下几点:
public static class KeyByComparator<T> implements Comparable<KeyByComparator<T>> {
private T target;
private Comparator<? super T> comparator;
public KeyByComparator(T target, Comparator<? super T> comparator) {
this.target = target;
this.comparator = comparator;
}
@Override
public int compareTo(KeyByComparator<T> other) {
return this.comparator.compare(this.target, other.target);
}
}
public static <T> Function<T, KeyByComparator<T>> keysByComparator(Comparator<? super T> comparator) {
return t -> new KeyByComparator<T>(t, comparator);
}
所以他们可以这样使用它:
public static final Comparator<Person> LEGACY_COMPARATOR = ...;
// ...
Collections2.sortBy(persons, Collections2.keysByComparator(LEGACY_COMPARATOR));
// Ignore the fact that regular sort would be shorter
// Collections.sort(persons, LEGACY_COMPARATOR)
但要实现这一点,我必须公开KeyByComparator<T>
。
如果我不想公开KeyByComparator<T>
课怎么办?这是我试过的:
public static <T, K extends Comparable<? super K>> Function<T, K>
keysByComparator2(Comparator<? super T> comparator) {
return t -> new KeyByComparator<T>(t, comparator);
}
但是它给出了这个编译错误:
Type mismatch: cannot convert from Collections2.KeyByComparator<T> to K
返回值是否有一些奇特的泛型类型约束?