For whatever reasons, SO bumped your question just a couple minutes ago. In 2021 you probably would not use Vector
any more, but List
. Actually both of them have subList(start,end)
method (even in Java 7 what the link points to), so practically you would just loop over vector/list in row-sized steps and use this method.
Also, you might fancy using streams so instead of initializing the result variable in a separate line, the stream collector does that for you:
List<Integer> vector=Arrays.asList(1,2,3,4,5,6,7,8);
int rowSize=4;
List<List<Integer>> matrix=IntStream.range(0, vector.size()/rowSize)
.mapToObj(row->vector.subList(row*rowSize, (row+1)*rowSize))
.collect(Collectors.toList());
System.out.println(matrix);
will output [[1, 2, 3, 4], [5, 6, 7, 8]]
.
Also, as Vector
can be constructed from List
, after all you can do that too:
Vector<Integer> vector=new Vector<Integer>(Arrays.asList(1,2,3,4,5,6,7,8));
int rowSize=4;
Vector<Vector<Integer>> matrix=new Vector<Vector<Integer>>(
IntStream.range(0, vector.size()/rowSize)
.mapToObj(row->new Vector<Integer>(vector.subList(row*rowSize, (row+1)*rowSize)))
.collect(Collectors.toList()));
System.out.println(matrix);
And of course in the background both of them do pretty much the same as a for
loop would have done:
Vector<Integer> vector=new Vector<Integer>(Arrays.asList(1,2,3,4,5,6,7,8));
int rowSize=4;
Vector<Vector<Integer>> matrix=new Vector<Vector<Integer>>();
for(int row=0;row<vector.size()/rowSize;row++)
matrix.add(new Vector<Integer>(vector.subList(row*rowSize, (row+1)*rowSize)));
System.out.println(matrix);