我见过很多排序对象列表的方法,如果您知道传入的键,或者至少知道传入的键的数量,这些方法就可以很好地工作。问题是在我的情况下,我不知道用户是否会发送1个或10个密钥。
目前,我为每个键都有一个巨大的switch语句,但显然它的伸缩性很差。它只是将一堆“thenComparing”链接在一起。
我在这里找到了一个示例,它看起来有点帮助,但我不知道如何构建一个比较器流。
How-to chain and apply a stream of comparators?
寻找一个链接或任何信息片段,以填补如何做到这一点的空白。
这一切都是在用户调用webservice时工作的,他们会这样调用它
https://host.com/path?sort=[{"attribute1": "ASC"}, {"attribute2": "DESC"}]发布于 2018-08-14 23:20:38
假设你有这样一个实体:
static class Person {
private final int age;
private final String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}您可以定义所有字段,并将这些字段映射到某个比较器:
Map<String, Comparator<Person>> map = new HashMap<>();
map.put("name_ASC", Comparator.comparing(Person::getName));
map.put("name_DESC", Comparator.comparing(Person::getName).reversed());
map.put("age_ASC", Comparator.comparingInt(Person::getAge));
map.put("age_DESC", Comparator.comparingInt(Person::getAge).reversed());然后有了你的输入,你可以这样做:
Comparator<Person> all = Stream.of("name_ASC", "age_DESC") // for example
.map(map::get)
.reduce(Comparator::thenComparing)
.orElse((a, b) -> 0); // or whatever you think appropriate在此之后对它们进行排序显然是不需要动脑筋的:
List<Person> persons = List.of(new Person(20, "Bob"), new Person(30, "Rose"));
// or Collections.sort(persons, all)
// persons.sort(all)
persons.stream().sorted(all).collect(Collectors.toList());发布于 2018-08-14 23:15:46
如果你能构建一个比较器列表,你可以使用如下代码:
public class MultiComparator<T> implements Comparator<T> {
private final List<Comparator<T>> comparators;
MultiComparator(List<Comparator<T>> comparators){
this.comparators = comparators;
}
@Override
public int compare(T t1, T t2) {
int r = 0;
for(Comparator c : comparators){
r = c.compare(t1,t2);
if(r != 0){
return r;
}
}
return r;
}
}(虽然不太像java8)
https://stackoverflow.com/questions/51844302
复制相似问题