I have a function which reads a CSV file and after some processing put the data into an
ArrayList<ArrayList<String>>
.
So I have this:
ArrayList = list of rows
sub-ArrayList<String> = list of columns
Now I have to do this (I'm guessing the java way of doing this is to
use a Comparator
): I need to sort these rows according to the string values of each field.
So, for example, if I have the rows (where each field is the final String in the ArrayList<ArrayList<String>>
structure):
Name|Birthdate|FathersName
John,2001-01-01,Steven
John,2001-01-01,Albert
the sorting action should reverse these two rows (because the first 2 fields are equal so the third field determines the order).
Any tips on how to do this would be greatly appreciated.
Answer: Arnaud Denoyelle's answer led me to the following generic solution
private Comparator<List<String>> comparator = new Comparator<List<String>>() {
@Override
public int compare(List<String> list1, List<String> list2) {
int size = list1.size();
int diff = 0;
for (int i=0; i<size; i++) {
diff = list1.get(i).compareTo(list2.get(i));
if (diff != 0) {
break;
}
}
return diff;
}
};
Note: this assumes that the rows being compared have the same number of columns, which in my case is a valid assumption.