-1

I have an ArrayList

List<List<Integer>> nestedlists = new ArrayList<>();

How to iterate this list using forEach and lambda Expression.

for example an Arraylist can be iterated as:-

List<Integer> singlelist = new ArrayList<>();
singlelist.forEach((ele)->System.out.println(ele)); 

How to do the same for ArrayList containing Arraylists.

3
  • 3
    Just the same way, list.forEach(x -> x.forEach(y -> System.out.println(y))); or perhaps with better names: list.forEach(sub -> sub.forEach(i -> System.out.println(i))); Commented Nov 13, 2019 at 13:31
  • 1
    @Holger or ... perhaps with better names: nestedLists.forEach(sub -> sub.forEach(i -> System.out.println(i))); ? Commented Nov 13, 2019 at 13:41
  • 1
    @Naman well, I didn’t want to change what’s perhaps given by the task. However, if we change the name, it would be even better to have a name which reflects the purpose of the list, rather than the fact that it is a nested list, which we can already derive from its type. Commented Nov 13, 2019 at 13:44

1 Answer 1

3

You can use Streams with flatMap:

list.stream()
    .flatMap(List::stream)
    .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

2 Comments

Which one will have better performance using streams or the otherway
@SomilGarg Are you really concerned about the performance of a System.out.print? The difference between the two would anyway be trivial, given the task executed. Even if you want, you can rather benchmark them and test them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.