192. Filtering nested collections with Streams
This is a classical problem in interviews that usually starts from a model, as follows (we assume that the collection is a List
):
public class Author {
private final String name;
private final List<Book> books;
...
}
public class Book {
private final String title;
private final LocalDate published;
...
}
Having List<Author>
denoted as authors
, write a stream pipeline that returns the List<Book>
published in 2002. You already should recognize this as a typical problem for flatMap()
, so without further details, we can write this:
List<Book> book2002fm = authors.stream()
.flatMap(author -> author.getBooks().stream())
.filter(book -> book.getPublished().getYear() == 2002)
.collect(Collectors.toList());
From Problem 185, we know that wherever flatMap()
is useful, we should also consider the JDK 16’s mapMulti()
. Before checking the following snippet of code, challenge...