简体   繁体   English

有一个Java数组列表; 如何按每个数组的最后一个元素排序?

[英]Have a List of Arrays in Java; How to Sort By the Last Element of Each Array?

I have a snippet of code which looks as follows: 我有一段代码,如下所示:

List<int[]> v1v2weighting = new ArrayList<int[]>();

for(int i = 0; i < size; i++){
    for(int j = 0; j < size; j++){
        int[] a = {i,j,graph[i][j]};
        v1v2weighting.add(a);
    }
}

After this concludes, I have a list of 3-element arrays, where the final element in each array is the weighting. 总结之后,我得到了一个由3个元素组成的数组的列表,其中每个数组中的最后一个元素是权重。 I'd now like to sort this list by the weighting, ie arrive at a finished list where for every element e, e_i[2] ≤ e_(i+1)[2]. 我现在想按权重对该列表进行排序,即得出一个完成的列表,其中每个元素e的e_i [2]≤e_(i + 1)[2]。 Is there a simple way to perform an operation like this in Java? 有没有简单的方法可以在Java中执行类似的操作? I've come across collections.sort() while looking for a solution, but this seems to only work in the event that I'm dealing with a list of comparables such as integers. 在寻找解决方案时,我遇到了collections.sort(),但这似乎仅在我要处理可比较对象(例如整数)列表的情况下才起作用。 Any help is appreciated. 任何帮助表示赞赏。

For sorting List in Java 1.7, you may use the following code segment. 为了在Java 1.7中对List进行排序,可以使用以下代码段。

Collections.sort(v1v2weighting, new Comparator<int[]>() {
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o1[2], o2[2]); // suppose all your arrays has at least 3 elements
    }
}

In fact, you may implement any sorting mechanism using this method. 实际上,您可以使用此方法实现任何排序机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM