我有2个比较器:
Comparator<? super MyClass> COMPARATOR_BY_PRIORITY =
Comparator.nullsFirst(
Comparator.comparing(c -> c.isEmpty() ? null : -c.getPriority())
);
Comparator<? super MyClass> COMPARATOR_BY_PRICE =
Comparator.nullsFirst(
Comparator.comparing(c -> c.isEmpty() ? null : c.getPrice())
);
并且我想将它们组合在一起,以便使用组合的比较器将按优先级对项目进行排序,并在按价格进行优先级相同的项目之间进行排序。如何创建组合比较器?
我正在尝试类似的东西:
Comparator<? super MyClass> COMBINED_COMPARATOR =
COMPARATOR_BY_PRIORITY.thenComparing(COMPARATOR_BY_FARE);
最佳答案
正如@tobias_k指出的,它在没有?的情况下有效超:
Comparator<MyClass> COMPARATOR_BY_PRIORITY =
Comparator.nullsFirst(
Comparator.comparing(c -> c.isEmpty() ? null : -c.getPriority())
);
Comparator<MyClass> COMPARATOR_BY_PRICE =
Comparator.nullsFirst(
Comparator.comparing(c -> c.isEmpty() ? null : c.getPrice())
);
Comparator<MyClass> COMBINED_COMPARATOR =
COMPARATOR_BY_PRIORITY.thenComparing(COMPARATOR_BY_FARE);