Given 是一个通用数据类型,看起来像这样:HashMap<EdgeTuple, Double> edgeList
其中 tuple 是一个 EdgeTuple 类,而 Double 是一个对任务不重要的权重:
class EdgeTuple{
int label1;
int label2;
public EdgeTuple(int label1, int label2){
int min = Math.min(label1, label2);
int max = Math.max(label1, label2);
this.label1 = min;
this.label2 = max;
}
}
因此,正如您所见,元组的第一个位置已经具有较小的值。我想要做的是对最终入场顺序应如下所示的列表进行排序:
条目 0:[(0,something);some_weight]
条目 1:[(1,something);some_weight]
...
条目 n-1:[(last_value,something);some_weight]
所以基本上我需要做的是根据第一个值对元组进行升序排序。 我已将关于此主题的最喜欢的现有答案标为红色,但仍然找不到任何令人满意的答案。
一个可能的解决方案是依靠比较器,像这样:
Comparator<Tuple> myComparator = new Comparator<Tuple>() {
public int compare(Tuple t1, Tuple t2) {
//the comparison rules go here
}
};
Collections.sort(tupleList, myComparator);
每对元组的比较似乎效率不高。所以我的问题是,你知道任何其他排序方法吗?也许一些新的数据类型可以为给定的任务提供合适的、性能更高的接口(interface)?
谢谢
最佳答案
您可以在EdgeTuple
中实现Comparable
接口(interface):
public static class EdgeTuple implements Comparable<EdgeTuple> {
int label1;
int label2;
public EdgeTuple(int label1, int label2){
int min = Math.min(label1, label2);
int max = Math.max(label1, label2);
this.label1 = min;
this.label2 = max;
}
@Override
public int compareTo(EdgeTuple o) {
return this.label1 - o.label1;
}
}
并使用 TreeMap
存储预排序的元组映射,而不是每次都对其进行排序。
关于java - 在java中对元组列表进行排序的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982382/