Java 使用两个索引对列表对进行排序
Java sort a list of pairs using both indexes
我想根据两个索引对 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 + ")";
}
}
将Collections.sort
与比较器构造函数一起使用,如下所示:
Collections.sort(list,
Comparator.comparing((Pair<Long, Long> p) -> p.first)
.thenComparing(p -> p.second));
更新
或者,按照下面评论中的建议,您可以使用 List.sort
,它比上面使用的实用方法更简洁。
list.sort(Comparator.comparing((Pair<Long, Long> p) -> p.first)
.thenComparing(p -> p.second));
我想根据两个索引对 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 + ")";
}
}
将Collections.sort
与比较器构造函数一起使用,如下所示:
Collections.sort(list,
Comparator.comparing((Pair<Long, Long> p) -> p.first)
.thenComparing(p -> p.second));
更新
或者,按照下面评论中的建议,您可以使用 List.sort
,它比上面使用的实用方法更简洁。
list.sort(Comparator.comparing((Pair<Long, Long> p) -> p.first)
.thenComparing(p -> p.second));