【发布时间】:2021-08-21 07:01:22
【问题描述】:
我想根据两个索引对List<Pair<Long, Long>> list = new ArrayList<Pair<Long, Long>>(); 进行排序,首先根据第一个索引,如果第一个索引相等,则使用 Java 8 lambda 函数根据第二个索引。
我可以很容易地只按第一个索引排序:
Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1:0);
如果我想根据两个索引进行排序
Collections.sort(list,(o1, o2) -> o1.first < o2.first ? -1 : o1.first == o2.first ? (o1.second < o2.second ? -1 : 0) : 0);
但我认为这不是正确的做法。有人可以提供更好的语法吗?
对定义:
class Pair<Type1, Type2> {
Type1 first;
Type2 second;
Pair(Type1 f, Type2 s) {
this.first = f;
this.second = s;
}
public String toString() {
return "(" + this.first + ", " + this.second + ")";
}
}
【问题讨论】:
-
当您看到比较器有时返回负数但从不返回正数时,您可以判断它已损坏。这显然违反了对称性要求。