Let's say I have a Shelf
class and each Shelf
has multiple Book
s.
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 Shelf
s, 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.
Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the list into stream and add it to the list. Now convert this list into stream using stream() method. Now flatten the stream by converting it into list using collect() method.
Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Pipelining − Most of the stream operations return stream itself so that their result can be pipelined.
The stream API allows you to perform operations on collections without external iteration. In this case, we're performing a filter operation which will filter the input collection based on the condition specified.
You can use flatMap
for this
shelves.stream()
.flatMap(s -> s.getBooks().stream())
.collect(Collectors.toList());
The streaming process is quite simple : s -> s.getBooks().stream()
makes a stream for each book on each shelf, flatMap
flattens everything, and collect(Collectors.toList())
stores the result in a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With