我想对按一个属性升序,然后按另一个属性降序的对象列表进行排序.
例如,假设以下列表为(age, name)
:
(25, Alice), (25, Bob), (30, Charlie), (25, David), (30, Eve)
我试着按年龄升序,然后按名字降序,如下所示:
(25, David), (25, Bob), (25, Alice), (30, Eve), (30, Charlie)
我试着使用Stream.sorted
和Comparator
来实现这一点,但我不确定如何在不反转前面的比较器的情况下反转Comparator.thenComparing
.
看一下这个例子:
import java.util.Comparator;
import java.util.List;
public class Dummy {
private 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; }
@Override
public String toString() { return "(" + age + ", " + name + ")"; }
}
public static void main(String[] args) {
var people = List.of(
new Person(25, "Alice"),
new Person(25, "Bob"),
new Person(30, "Charlie"),
new Person(25, "David"),
new Person(30, "Eve")
);
System.out.println(people);
var sortedPeople = people
.stream()
.sorted(
Comparator
.comparing(Person::getAge)
.thenComparing(Person::getName)
.reversed()
)
.toList();
System.out.println(sortedPeople);
}
}
如您所见,我对比较器应用了reversed
,但得到的比较结果为
age by descending, then name by descending:个
(30, Eve), (30, Charlie), (25, David), (25, Bob), (25, Alice)
但正如我上面所说的,我试图实现的比较是
age by ascending, then name by descending:个
(25, David), (25, Bob), (25, Alice), (30, Eve), (30, Charlie)