How to sort a vector of vectors?

In Java, I wonder how to sort the vectors of vectors in a particular column, where one vector is used as a row, and one vector is used to store all row vectors, for example.

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, for example. Column2 .

thanks

+6
source share
5 answers

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

But in the end, you will be much better off if you get rid of the Vector -in- Vector construct and replace the internal Vector with your own class that represents the data you want to represent. Then you write Comparator<MyClass> , which will be much easier to interpret ("oh, this comparator is compared based on the first name" and not "why does this comparator take an element in index 1 and compare it? What does that mean ??").

+8
source

I think you want to sort in "main" and not in "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 }}); 
+4
source

(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)); // will sort according to "column2" 

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.

+2
source

Vectors may not be the best view of your table. See Glazed Lists .

0
source

Create a reusable comparator that you can use to sort by any index in Vector (or List or Array). Column Comparator does this for you.

0
source

Source: https://habr.com/ru/post/888320/


All Articles