how can i sort an ArrayList of integer array based on the last integer in the integer array?
ArrayList<int[]> paths = new ArrayList<int[]>();
paths.add(new int[]{0,0,0,0,4});
paths.add(new int[]{0,0,0,0,2});
paths.add(new int[]{0,0,0,0,1});
paths.add(new int[]{0,0,0,0,3});
the resulting ArrayList would contain: [0,0,0,1] [0,0,0,2] [0,0,0,3] [0,0,0,4]
Implement a Comparator
and use Collections.sort
. Or do both at once:
Collections.sort(paths, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return (Integer)(a[a.length-1]).compareTo(b[b.length-1]);
}
});
Here is a version with a comparator that doesn't do autoboxing or casting:
public class Sorter {
public static void main(String[] args) {
ArrayList<int[]> paths = new ArrayList<int[]>();
paths.add(new int[] { 0, 0, 0, 0, 4 });
paths.add(new int[] { 0, 0, 0, 0, 2 });
paths.add(new int[] { 0, 0, 0, 0, 1 });
paths.add(new int[] { 0, 0, 0, 0, 3 });
Collections.sort(paths, new Comparator<int[]>() {
private static final int INDEX = 4;
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[INDEX], o2[INDEX]);
}
});
for (int[] is : paths) {
System.out.println(Arrays.toString(is));
}
}
}
Will result in:
[0, 0, 0, 0, 1]
[0, 0, 0, 0, 2]
[0, 0, 0, 0, 3]
[0, 0, 0, 0, 4]
使用 Java-8
paths.sort(Comparator.comparingInt(a -> a[a.length - 1]));
查看java.util.Collections.sort(List list, Comparator c) ......您需要做的就是编写一个比较器来比较您的两个数组,其余的都是小菜一碟。
First of all in your code it should be paths.add(...)
not path.add(...)
If you don't want to implement Comparator
you could always write a method yourself. If efficiency isn't important this could work (bubble sort - obviously it could be much better using a better sorting algorithm):
public ArrayList<int[]> sort() {
ArrayList<int[]> sortedArray = this;
boolean switched = true;
while(switched) {
switched = false;
for(int i=0; i<sortedArray.size()-1; i++)
int[] a = sortedArray.get(i);
int[] b = sortedArray.get(i+1);
if(a[a.length]>b[b.length]) {
sortedArray.set(i, b);
sortedArray.set(i+1, a);
switched = true;
}
}
return sortedArray;
}
This goes through the ArrayList and checks if the last element of each pair of consecutive arrays is in the right order. If so, it checks the next pair; if not, it switches the two arrays int the ArrayList. It continues going through the ArrayList until it doesn't have to do anymore switches; at this point the ArrayList is sorted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.