[英]Convert ArrayLIst of objects to String 2D Array
I'm trying to convert an ArrayList of type Car to a 2D Array. 我正在尝试将Car类型的ArrayList转换为2D数组。 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 : 不幸的是,我没有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"));,
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++;
}
}
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();
....
}
The inner loop is not required. 不需要内部循环。 You want to map each Car
field as column values of the 2d array. 您想要将每个Car
字段映射为2d数组的列值。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.