Reputation: 108
I was notified that is possible to create "infinite" ArrayLists inside others, such as in the code below:
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Object>>>>> List = new ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Object>>>>>();
}
}
And I want know about how to iterate them (with foreach or other loop types)
Upvotes: 0
Views: 174
Reputation: 143
IMHO, if someone writes such structures - it's some kind of a maniac. But still, you can follow this kind of pattern in order to traverse:
@Test
public void test4() {
List<String> list1 = new ArrayList<>();
list1.add("abc");
list1.add("def");
List<List<String>> list2 = new ArrayList<>();
list2.add(list1);
list2.stream().flatMap(Collection::stream).forEach(System.out::println);
}
```
Upvotes: 2
Reputation: 2271
You could try to traverse it like a composite:
public static void traverse(ArrayList<T> arg) {
arg.forEach(
(n) -> if (n instanceof ArrayList) {
traverse(n)
} else {
doStomething(n)
}
);
}
Upvotes: 3