根据未知数量的键对对象列表进行排序

can*_*n14 5 java java-8

我已经看到了很多方法来排序一个工作正常的对象列表,如果你知道传入的键或至少传入的键数.在我的情况下问题我不知道用户是否会发送1或10个密钥.

目前我对每个键的数量都有一个巨大的switch语句,但显然它的扩展程度非常大.它只是把一堆'thenComparing'连在一起.

我在这里找到了一个示例,看起来有点帮助,但我不知道如何构建比较器流.

如何链接和应用比较器流?

寻找链接或真正的任何信息将填补如何做到这一点的空白.

这一切都来自用户调用webservice,他们会称之为

https://host.com/path?sort=[{"attribute1": "ASC"}, {"attribute2": "DESC"}]
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 6

假设你有这样一个实体:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以定义所有字段并将它们映射到某个比较器:

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());
Run Code Online (Sandbox Code Playgroud)

然后有了你的输入,你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

在这之后对它们进行排序显然是没有道理的:

 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());
Run Code Online (Sandbox Code Playgroud)