将对象的ArrayLIst转换为String 2D Array

时间:2018-08-03 20:49:27

标签: java arrays

我正在尝试将Car类型的ArrayList转换为2D Array。不幸的是,我没有Java8。我在Java 7上,而在Java 8上,应该有一种简单的方法来实现它:

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

逻辑

     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++;
          }
      }

所需的Ouput: enter image description here

2 个答案:

答案 0 :(得分:1)

我不明白为什么不能使用数组列表映射到表,但是构造数组可以执行以下操作:

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();
    ....
}

答案 1 :(得分:1)

不需要内部循环。您想将每个<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="carousel" class="carousel slide" data-ride="carousel"> <div runat="server" id="CarouselHtml" class="carousel-inner" style="height: 500px;"> </div> <div id="item" class="item" <a href="#carousel" ID="tagLeft" onclick="waitchange();" class="left carousel-control" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a href="#carousel" ID="tagR" class="right carousel-control" onclick="waitchange();"; data-slide="next"> <span class="glyphicon glyphicon-chevron-right" ></span> </a> </div> </div>字段映射为2d数组的列值。

所以改变:

Car

至:

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