Reputation: 13
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]
Upvotes: 1
Views: 9551
Reputation: 1654
Using Java-8
paths.sort(Comparator.comparingInt(a -> a[a.length - 1]));
Upvotes: 3
Reputation: 836
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.
Upvotes: 0
Reputation: 22830
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]
Upvotes: 4
Reputation: 6230
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]);
}
});
Upvotes: 7
Reputation: 7396
Check out java.util.Collections.sort(List list, Comparator c)... all you need to do is write a Comparator that compares two of your Arrays and the rest is a piece of cake.
Upvotes: 0