简体   繁体   中英

How to create matrix from java vector of vectors (Multidimentional Vector)

am trying to create vector of Vectors(2d) in java like multidimensional array. then to assign values to specific position in that matrix like what we do using matrix[i][j] in 2D array Any help.

My data in one Vector:

n = [a, b, c, d, e, f, g , h]

I want to create 2D Vector to represent vector m =

  • abcd
  • efgh

You can create a 2D Vector using the following:

Vector<Vector<Integer>> vector2D = new Vector<Vector<Integer>>(10);

This will create a Vector of size 10 which will contain Vectors with Integer(Vector) values. Before setting a value at a particular index, you need to create a Vector of Integer and set at the row position(2 in your case).

vector2D.add(2, new Vector<Integer>(10));

You can then set a value at the column index using the following syntax:

Vector<Integer> rowVector = vector2D.get(2);
rowVector.add(3, 5);

Here we first get the Vector of Integers (Vector) at index 2. Then add the value at the index 3 in the Vector of Integers(Vector).

Hope this explains.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM