I know how to sort an array that has two columns:
Arrays.sort(myarray, new Comparator<String[]>() {
@Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[0];
String time2 = entry2[0];
return time2.compareTo(time1);
}
});
This sorts the arrray by the first column.
But what if I have more columns? E.g.
myarray[0][0]= +3620205252
myarray[0][1]= 32534
myarray[0][2]= Franco Nera
myarray[0][3]= 183
myarray[1][0]= +3658300234
myarray[1][1]= 4334
myarray[1][2]= Judy Moira
myarray[1][3]= 28
etc..
I want to sort this e.g. by the second column, or the fourth column…
I can try to work this out by creating a new array[1st+3rd+4th column][2nd column] and then sort it with the above solution, then take the elements apart, but that is too circumstantial.
It’s the same thing as with two columns, but with more columns: you can sort on as many, or as few, columns as you want, as long as your comparator checks the columns you care about.
To sort by multiple columns you need to decide the comparison order and return the
compareToresult as soon as you have unequal columns.Tangentially, why would you use arrays for this? It’s Java, might as well use like an object or something.