简体   繁体   中英

How to iterate the vector of vectors and get the output in the below scenario?

I have to get the first element of each vector and add into another vector and continue till mainVector ends

mainVector -- > [[1,Allen,2000,10],[2,Joe,3000,20],[3,King,4000,40]] [Vector(Vectors)]

output should be -- > [[1,2,3],[Allen,Joe,King],[2000,3000,4000],[10,20,40]] [Vector(Vectors)]

int i=0;
Vector outputVector = new Vector();
for(int p = 0; p < mainVector.size(); p++)        
{
       Vector second = new Vector();
       for(int h = 0; h < mainVector.size(); h++) 
       {
          eachVector = mainVector.get(h);
          String eachElement = eachVector.get(i);
          second.add(eachElement);
       }
       outputVector.add(second);
    i++;       
}

Try this.

int i = 0;
Vector outputVector = new Vector();
for (int p = 0; p < ((Vector)mainVector.get(0)).size(); p++) {
    Vector second = new Vector();
    for (int h = 0; h < mainVector.size(); h++) {
        Vector eachVector = (Vector)mainVector.get(h);
        Object eachElement = eachVector.get(i);
        second.add(eachElement);
    }
    outputVector.add(second);
    i++;
}

You don't need 3 index variables, as you have a 2 dimensional data structure:

Vector outputVector = new Vector();
for (int i = 0; i < mainVector.size(); i++) {
    outputVector.add(new Vector());
    for (int j = 0; j < mainVector.get(0).size(); j++) {
        ((Vector) outputVector.get(i)).add(mainVector.get(i).get(j));
    }
}

I have to point out that this seems very old school Java. Unless you have a legacy project, consider using something Vector<Vector<Object>> outputVector . Also you probably want to use List as Vector is now considered obsolete

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