1

If I have a class Book that has inside it a List of Page objects, how can I generate a collection of objects of Page given a collection of Book objects, using Java 8 features such as Streams, Collectors, lamdas etc.? I know how to do this using pre-Java 8 techniques, but I would like to see it done with one line with the Java 8 features.

Thank you.

xlm
  • 5,564
  • 13
  • 48
  • 52
ITWorker
  • 905
  • 2
  • 15
  • 39

1 Answers1

3

Assuming that a Book has a getPages method returning a collection of Pages, you need to use flatMap method to "flatten" collections of pages inside a collection of books:

Stream<Page> pages = books.stream().flatMap(b -> b.getPages().stream());

This produces a stream; if you need a collection, use list collector to construct it.

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • This worked great, flatMap was the missing ingredient. I was hitting a dead end with forEach on the Books. Thanks for a constructive answer. – ITWorker Jan 14 '17 at 19:57