0

I'm trying to convert an ArrayList of type Car to a 2D Array. Unfortunetly I don't have Java 8. I'm on java 7 and with java 8 there's supposed to be an easy way to do it which is :

String[][] stringArray = miniTable.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);

ArrayList:

miniTable = new ArrayList<Car>();
      miniTable.add(new Car("1123", "New York, NY", "Green"));
      miniTable.add(new Car("3321", "Tampa, FL", "Blue"));
      miniTable.add(new Car("3346", "Atlanta, GA", "Red"));,

Logic

     int count=0;
      String[][] content = new String [3][5];
      //Convert regular array  to [][]
      for(int i=0;i<3;i++)
      {
          for(int j=0;j<5;j++)
          {
              if(count == miniTable.size()) break;
                content[i][j]= miniTable.get(i).getNumber();
                content[i][j]= miniTable.get(i).getOrigin();
                content[i][j]= miniTable.get(i).getColor();                   
                count++;
          }
      }

Desired Ouput: enter image description here

0

2 Answers 2

1

I don't see why you can't use the array list to map to the table but to construct the array you can do something like this:

String[][] content = new String [3][5];
for(int i = 0; i < miniTable.size(); i++)
{
    Car car = miniTable.get(i);
    content[i][0] = car.getName();
    content[i][1] = car.getManufacturer();
    ....
}
Sign up to request clarification or add additional context in comments.

3 Comments

How would you map it using java 7? you solution worked it was very simple. Thanks
@PatricioVargas Welcome. I meant you probably don't need this intermediate step of constructing the 2D array to visualize in on the table but you didn't show more code and I can't say. Anyway if this works it is fine.
Your solution worked, it's simple. I was just curious on how to do it with the map thing. Thanks for taking your time to answer!
1

The inner loop is not required. You want to map each Car field as column values of the 2d array.

So change :

for(int j=0;j<5;j++)
{
    if(count == miniTable.size()) break;
    content[i][j]= miniTable.get(i)+"";
    count++;    
}

to :

int j=0;
Car car =  miniTable.get(i);
content[i][j++]= car.getName();
content[i][j++]= car.getOrigin();
content[i][j++]= car.getColor();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.