简体   繁体   中英

How iterate an ArrayList inside various others ArrayLists?

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM