2

I was wondering, How can we iterate a multilevel list using stream API in Java 8

For example,

List<List<String>> multiList = new ArrayList<>();
List<String> names= Arrays.asList("a","b");
List<String> fewMoreNames= Arrays.asList("e","f");
multiList.add(names);
multiList.add(fewMoreNames);

As per Java 8, I should go something like below

multiList.stream().... ?

I wanted to do this fluently(using internal iteration).Any explanation would be appreciated.

user2051604
  • 51
  • 1
  • 1
  • 5
  • What do you want to achieve with this iteration? It hard to answer without knowing that. – Eran Feb 05 '15 at 11:13
  • I was wondering if it is possible or not using internal java8 iterators and streams. List of List can be a very common data structure in any programming solution.This question is generated from curosity:) – user2051604 Feb 05 '15 at 11:18
  • Of course it's possible, but there are many ways streams can be used for many purposes, so you'll have to ask a more specific question to get an answer. – Eran Feb 05 '15 at 11:20

1 Answers1

3

Got it folks, it was easy one. I was not looking at the API closely. One of the solution is

multiList .stream().forEach((x) -> x.stream().forEach(System.out::println));

user2051604
  • 51
  • 1
  • 1
  • 5
  • 2
    The preferred way is `multiList .stream().flatMap(List::stream).forEach(System.out::println);` as it’s one operation rather than multiple nested operations. You may notice the difference as soon as you want to perform a different action than `forEach`. – Holger Feb 05 '15 at 14:34