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
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?").
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
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With