0

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.

Somil Garg
  • 474
  • 4
  • 12
  • 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)));` – Holger Nov 13 '19 at 13:31
  • 1
    @Holger or ... *perhaps with better names: `nestedLists.forEach(sub -> sub.forEach(i -> System.out.println(i)));`* ? – Naman Nov 13 '19 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. – Holger Nov 13 '19 at 13:44

1 Answers1

3

You can use Streams with flatMap:

list.stream()
    .flatMap(List::stream)
    .forEach(System.out::println);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Which one will have better performance using streams or the otherway – Somil Garg Nov 13 '19 at 13:42
  • 2
    @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. – Naman Nov 13 '19 at 13:44