How do I access a specific element from a nested ArrayList

2.3k Views Asked by At

I have two ArrayLists

private ArrayList<ArrayList<String> dataList = new ArrayList<>();
//This is a class variable

ArrayList<String> dataRow = new ArrayList<>();
//This is a method variable

I add items to dataRow

dataRow.add("number");
dataRow.add("firstName");
dataRow.add("surname");
dataRow.add("dateStart");
dataRow.add("dateEnd");

and then I add each dataRow to dataList resulting in an ArrayList of ArrayLists

dataList.add(dataRow);

My Question is:

I need to select just elements 3 and 4 from each dataRow and I can't find any code that works.

I have tried

for (ArrayList<String> eachRow : dataList)
{
    For (String eachElement : eachRow)
    (
        System.out.println(eachElement)
    }
}

All this does is print out all the elements

I have also tried other code such as

dataList.get(eachElement)

this throws a no suitable method error in netbeans

3

There are 3 best solutions below

0
On BEST ANSWER

I worked it out as soon as I had posted this.

The code in the inner for loop should be:

System.out.println(eachRow.get(4));
0
On

You can have a class to store values like below,

class ExtractedValue {

  private String value3;
  private String value4;

  public ExtractedValue(String value3, String value4) {
    this.value3 = value3;
    this.value4 = value4;
  }

  public String getValue3() {
    return value3;
  }

  public String getValue4() {
    return value4;
  }
}

And use the below to extract the 3rd and 4th values,

List<ExtractedValue> extracted= dataList.stream().map(l -> new ExtractedValue(l.get(3), l.get(4)))
            .collect(Collectors.toList());

To print you can use the below,

extracted.stream().forEach(e -> {
        System.out.println(e.getValue3());
        System.out.println(e.getValue4());
    });
0
On

Assuming you want to extract only two array elements, you could use a simple POJO for that:

class YourPojo { // rename it to something self-explanatory
  private String field3;
  private String field4;   
  // getters & setters
}

Then define an utility method extracting the data into your POJO from the raw array:

static YourPojo extractYourPojo(List<String> rawData){
    YourPojo pojo = new YourPojo();
    pojo.setField3(rawData.get(3));
    pojo.setField4(rawData.get(4));
    return pojo;
} 

Then you can use the method as follows:

List<YourPojo> extracted = 
    dataList.stream()
            .map(ClassWithUtilityMethod::extractYourPojo)
            .collect(toList());