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
  • 6,854
  • 14
  • 53
  • 55
ITWorker
  • 965
  • 2
  • 16
  • 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
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 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