(why do people still use Vector
and avoid generics? I should ask that question on SO... ;) )
Let me suggest a modern refactoring first:
List<List<String>> main = new ArrayList<List<String>>();
List<String> row = new ArrayList<String>();
row.add("Column1");
row.add("Column2");
row.add("Column3");
main.add(row);
Now we can look at Collections.sort(Comparator<T> comp)
which will do the sorting of main
. We just have to implement a Comparator class that is able to compare two rows according to our parameter - which is a certain column, in our case:
public class MyComparator implements Comparator<List<String>> {
private int columnIndex = 0;
public MyComparator(int columnIndex) {this.columnIndex = columnIndex;}
@Override
public int compare(List<String> thisRow, List<String> otherRow) {
return thisRow.get(columnIndex).compareTo(otherRow.get(columnIndex));
}
}
Use the comparator like this:
Collections.sort(main, new MyComparator(1)); // will sort according to "column2"
Note - this is an incomplete implementation, I don't check if the index values are valid and if all rows have the same size .. should be done in production code.