title: Using Java streams with composed collections
body: <p>I'm looking to use Java streams to solve this type of problem:</p>
  
  <p>I have a List of Library objects.</p>
  
  <p>The Library class contains a Map of Sections.  The Sections contains a List of BookShelf objects.  The BookShelf contains a Map of Book objects.</p>
  
  <pre><code>class Library {
      Map&lt;String, Section&gt; sections = new HashMap&lt;String, Section&gt;();
      String name;
      public String toString() {
          return name;
      }
  }
  
  class Section {
      List&lt;BookShelf&gt; bookShelves = new ArrayList&lt;BookShelf&gt;();
  }
  
  class BookShelf {
      Map&lt;String, Book&gt; books = new HashMap&lt;String, Book&gt;();
  }
  
  class Book {
      String name;
      Book(String name) {
         this.name = name;
      }
  }
  </code></pre>
  
  <p>What I want to find out is all Library objects that have the Book called "Java 8".    I think that this is a query that could be answered using streams, however, coding various stream calls I get a collection of Book objects, not the root Library objects.   </p>
  
  <p>Are streams suitable for using embedded objects and collections?  How would I achieve this?  </p>
  
  <p>Below is a simple code, that uses traditional loops to find the answer:</p>
  
  <pre><code>List&lt;Library&gt; libraries = new ArrayList&lt;Library&gt;();
  
  Library lib = new Library();
  lib.name = "Houston Central";
  libraries.add(lib);
  
  Section section = new Section();
  lib.sections.put("Reference", section);
  
  BookShelf shelf = new BookShelf();
  section.bookShelves.add(shelf);
  
  Book book = new Book("Java 8");
  shelf.books.put("Java 8", book);
  
  book = new Book("Java 7");
  shelf.books.put("Java 7", book);
  
  
  /*
   * Search for a Library containing a specific book
   * using traditional loops.
   */
  for(Library library : libraries) {
      for (Section sec : library.sections.values()) {
          for (BookShelf bookShelf : sec.bookShelves) {
              for (Book b : bookShelf.books.values()) {
                  if (b.name.equals("Java 8")) {
                      System.out.println("Book is contained in Library " + library);
                  }
              }
          }
      }
  }
  </code></pre>