(why do people still use Vector and avoid generics? I have to ask this question on SO ...;))
Let me first suggest modern refactoring:
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 sort main . We just need to implement the Comparator class, which can compare two rows according to our parameter - which is a specific 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 as follows:
Collections.sort(main, new MyComparator(1));
Note. This is an incomplete implementation, I do not check if the index values ββare valid, and if all rows are the same size .. must be executed in production code.
source share