Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Vector of Vectors?

In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

 Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);

Then sort the variables in one of the columns e.g. Column2.

Thank you

like image 616
Barnesy Avatar asked May 17 '11 13:05

Barnesy


2 Answers

You could write a Comparator<Vector> that compares two Vector objects based on their second element and use Collections.sort(List,Comparator) with that.

But in the long run you'll be much better off if you get rid of the Vector-in-Vector construct and replace the inner Vector with a custom class that represents the data that you want it to represent. Then you'd write a Comparator<MyClass> which would be much easier to interpret ("oh, this comparator compares based on the first name" instead of "why does this comparator take the element at index 1 and compare that? What does that mean?").

like image 145
Joachim Sauer Avatar answered Sep 29 '22 03:09

Joachim Sauer


I guess you want to sort in 'main' rather than 'row':

Vector<String> row = new Vector<String>();
Vector<Vector<String>> main = new Vector<Vector<String>>();

Collections.sort(main, new Comparator<Vector<String>>(){
    @Override  public int compare(Vector<String> v1, Vector<String> v2) {
        return v1.get(1).compareTo(v2.get(1)); //If you order by 2nd element in row
}});
like image 32
卢声远 Shengyuan Lu Avatar answered Sep 29 '22 03:09

卢声远 Shengyuan Lu