我想List<Pair<Long, Long>> list = new ArrayList<Pair<Long, Long>>();
根据两个索引对 a 进行排序,首先根据第一个索引,如果第一个索引相等,则根据第二个索引使用 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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句