统一排序
多个字段按照同一逻辑排序
public enum SortEnum {
ASC {
@Override
@SafeVarargs
public final <T, V extends Comparable<V>> void sort(List<T> list, Function<T, V>... sortKeys) {
Comparator<T> comparators = Stream.of(sortKeys)
.map(Comparator::comparing)
.reduce(Comparator::thenComparing)
.orElseThrow(IllegalArgumentException::new);
list.sort(comparators);
}
},
DESC {
@Override
@SafeVarargs
public final <T, V extends Comparable<V>> void sort(List<T> list, Function<T, V>... sortKeys) {
Comparator<T> comparators = Stream.of(sortKeys)
.map(key -> Comparator.comparing(key, Comparator.reverseOrder())) // 降序
.reduce(Comparator::thenComparing)
.orElseThrow(IllegalArgumentException::new);
list.sort(comparators);
}
};
public abstract <T, V extends Comparable<V>> void sort(List<T> list, Function<T, V>... sortKey);
}
运行结果如下:
public static void main(String[] args) {
@Data
@AllArgsConstructor
@NoArgsConstructor
class M {
private int a;
private int b;
private int c;
}
List<M> list = new ArrayList<>();
list.add(new M(3, 2, 1));
list.add(new M(3, 3, 2));
list.add(new M(2, 1, 3));
SortEnum.ASC.sort(list, M::getA, M::getB);
System.out.println(list);
}
[M(a=2, b=1, c=3), M(a=3, b=2, c=1), M(a=3, b=3, c=2)]
组合排序
自定义选择排序的字段,并选择升降排序。
public enum SortEnum {
ASC {
@Override
public <T, V extends Comparable<V>> Comparator<T> getComparator(Function<T, V> sortKey) {
return Comparator.comparing(sortKey);
}
},
DESC {
@Override
public <T, V extends Comparable<V>> Comparator<T> getComparator(Function<T, V> sortKey) {
return Comparator.comparing(sortKey, Comparator.reverseOrder());
}
};
public abstract <T, V extends Comparable<V>> Comparator<T> getComparator(Function<T, V> sortKey);
private static <T> SortBuilder<T> build(List<T> list) {
return new SortBuilder<>(list);
}
private static class SortBuilder<T> {
private final List<Comparator<T>> comparators = new ArrayList<>();
private final List<T> list;
public SortBuilder(List<T> list) {
this.list = list;
}
public <V extends Comparable<V>> SortBuilder<T> add(Function<T, V> sortKey, SortEnum order) {
comparators.add(order.getComparator(sortKey));
return this;
}
public void sort() {
Comparator<T> combinedComparator = comparators.stream()
.reduce(Comparator::thenComparing)
.orElseThrow(IllegalArgumentException::new);
list.sort(combinedComparator);
}
}
}
运行结果如下:
public static void main(String[] args) {
@Data
@AllArgsConstructor
@NoArgsConstructor
class M {
private int a;
private int b;
private int c;
}
List<M> list = new ArrayList<>();
list.add(new M(3, 2, 1));
list.add(new M(3, 3, 2));
list.add(new M(2, 1, 3));
SortEnum.build(list)
.add(M::getA, SortEnum.ASC)
.add(M::getB, SortEnum.DESC)
.sort();
System.out.println(list);
}
//[M(a=2, b=1, c=3), M(a=3, b=3, c=2), M(a=3, b=2, c=1)]