迭代2d ArrayList中的值

  • 本文关键字:ArrayList 2d 迭代 java
  • 更新时间 :
  • 英文 :


我试图通过ArrayList (Sku,Name,Status)的ArrayList (deviceList)进行迭代和打印,我立即想要做一个嵌套循环,但不是语法。

ArrayList<String> deviceSku = new ArrayList<String>();
deviceSku.add("6767A");
deviceSku.add("93P51B");
deviceSku.add("10N8C");
deviceSku.add("85U20");
deviceSku.add("91H2D");

ArrayList<String> deviceName = new ArrayList<String>();
deviceName.add("Apple 9.7-Inch iPad Pro");
deviceName.add("Amazon Kindle Fire Kids Edition");
deviceName.add("LeapFrog Epic Learning Tablet");
deviceName.add("Amazon Kindle Fire HD 8");
deviceName.add("HP Envy Note 8");

ArrayList<String> deviceStatus = new ArrayList<String>();
deviceStatus.add("Available");
deviceStatus.add("Available");
deviceStatus.add("Available");
deviceStatus.add("Checked Out");
deviceStatus.add("Available");

ArrayList<ArrayList<String>> deviceList = new ArrayList();  
deviceList.add(deviceSku);
deviceList.add(deviceName);
deviceList.add(deviceStatus);

期望输出示例:

SKU: deviceList[0][0], Name: deviceList[1][0], Status: deviceList[2][0]
SKU: deviceList[0][1] ... and so on 

我建议不要使用2d列表。

创建类

public class Device {
private String sku, name;
private boolean available;
public Device(String sku, String name, boolean isAvailable) {
this.sku = sku; 
this.name = name;
this.available = isAvailable;
}
public String getStatusString() {
return available ? "Available" : "Checked out";
}

public String toString() {
return String.format("SKU: %s, Name: %s, Status: %s", this.sku, this.name, this.getStatusString());
}
}

然后使用一个列表

List<Device> devices = new ArrayList<Device>();
devices.add(new Device("6767A", "Apple 9.7-Inch iPad Pro", true));
...

当您想要打印它们时,只需迭代

devices.forEach(System.out::println)

如果你确定这3个数组列表的长度相同,你可以遍历这个长度,每次打印一行:

for (int i = 0; i < deviceList.get(0).size(); i++) {
System.out.printf("SKU: %s, Name: %s, Status: %s%n", deviceList.get(0).get(i), deviceList.get(1).get(i), deviceList.get(2).get(i));
}

输出:

SKU: 6767A, Name: Apple 9.7-Inch iPad Pro, Status: Available
SKU: 93P51B, Name: Amazon Kindle Fire Kids Edition, Status: Available
SKU: 10N8C, Name: LeapFrog Epic Learning Tablet, Status: Available
SKU: 85U20, Name: Amazon Kindle Fire HD 8, Status: Checked Out
SKU: 91H2D, Name: HP Envy Note 8, Status: Available

相关内容

  • 没有找到相关文章

最新更新