Let's say I have a Shelf class and each Shelf has multiple Books.
public class Shelf{
private String shelfCode;
private ArrayList<Book> books; //add getters, setters etc.
}
public class Book{
private String title;
}
Now, let's say from some method I have a List of Shelfs, each containing some books. How do I use stream to collect all the books to this list?
List<Shelf> shelves = new ArrayList<Shelf>();
Shelf s1 = new Shelf();
s1.add(new Book("book1"));
s1.add(new Book("book2"));
Shelf s2 = new Shelf();
s1.add(new Book("book3"));
s1.add(new Book("book4"));
shelves.add(s1);
shelves.add(s2);
List<Book> booksInLibrary = //??
I'm thinking something like
List<Book> booksInLibrary =
shelves.stream()
.map(s -> s.getBooks())
.forEach(booksInLibrary.addall(books));
but it doesn't seem to work, throwing a compilation error.