Home > Software engineering >  Iterate values in 2d ArrayList
Iterate values in 2d ArrayList

Time:04-26

I am attempting to iterate and print through an ArrayList (deviceList) of ArrayLists (Sku,Name,Status), immediatly I am wanting to do a nested loop but not on the syntax.

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

Example of desired output:

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

CodePudding user response:

If you know for sure that all the 3 arraylists are in the same length, you can just iterate over this length, and each time print one row:

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

Output:

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

CodePudding user response:

I would advise not to use 2d lists.

Create a class

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 toString() {
        return String.format("SKU: %s, Name: %s, Status: %s", this.sku, this.name, this.getStatusString());
    }
}

Then use one list

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

When you want to print them, then just iterate that

devices.forEach(System.out::println)
  •  Tags:  
  • java
  • Related