Reputation: 47
I have List of ArrayList Elements, see below.
List<List<String>> x = new ArrayList<List<String>>();
it contains some array list elements.
eg.
x.get(0)->[1,2,3,4],
x.get(1)->([5,6,7,8],
x.get(2)->[9,10,11,12],
x.get(3)->[13,14,15,16]
i want to access element 3 from x.get(0) or element 7 from x.get(1) how to call that??
Upvotes: 2
Views: 13164
Reputation: 69
//To directly access any list member using for loop instead of foreach loop
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i=0;i<list.size();i++){
for(int j=0;j<list.get(i).size();j++){
do_something_on(list.get(i).get(j);
}
}
Upvotes: 0
Reputation: 6033
Each element of your list is a list and has the same interface that provides List<T>
methods, e.g.
T get(int index)
boolean isEmpty()
void add(T element)
You can access element from the inner list by index
List<List<String>> x = new ArrayList<List<String>>();
// ... some data initialised
String element_0_3 = x.get(0).get(3);
Be aware that each List<String>
element needs to have been created before accessing it. For instance, in order to add a new String
at the [0,0] coordinates:
List<List<String>> x = new ArrayList<List<String>>();
List<String> x0 = new ArrayList<>();
x0.add("foo"); // add "foo" as the first string element
x.add(x0); // add x0 as the first List<String> element
You can also read values with an enhanced for
loop, without using the indexes:
List<List<String>> x = new ArrayList<List<String>>();
//...
for (List<String> ls : x) { // iteration on the x list
for (String s : ls) { // iteration on each intern list
System.out.println(s);
}
Upvotes: 2
Reputation: 1251
You can follow like...
List<List<String>> x = new ArrayList<List<String>>();
List<String> subX = x.get(7);
if(null != subX && subX.size() != 0) {
String element = subX.get(0);
}
Upvotes: 0