title: Java Streams: group a List into a Map of Maps
body: <p>How could I do the following with Java Streams?</p>
  
  <p>Let's say I have the following classes:</p>
  
  <pre><code>class Foo {
      Bar b;
  }
  
  class Bar {
      String id;
      String date;
  }
  </code></pre>
  
  <p>I have a <code>List&lt;Foo&gt;</code> and I want to convert it to a <code>Map &lt;Foo.b.id, Map&lt;Foo.b.date, Foo&gt;</code>. I.e: <em>group first by the <code>Foo.b.id</code> and then by <code>Foo.b.date</code></em>.</p>
  
  <p>I'm struggling with the following 2-step approach, but the second one doesn't even compile:</p>
  
  <pre><code>Map&lt;String, List&lt;Foo&gt;&gt; groupById =
          myList
                  .stream()
                  .collect(
                          Collectors.groupingBy(
                                  foo -&gt; foo.getBar().getId()
                          )
                  );
  
  Map&lt;String, Map&lt;String, Foo&gt;&gt; output = groupById.entrySet()
          .stream()
          .map(
                  entry -&gt; entry.getKey(),
                  entry -&gt; entry.getValue()
                          .stream()
                          .collect(
                                  Collectors.groupingBy(
                                          bar -&gt; bar.getDate()
                                  )
                          )
          );
  </code></pre>
  
  <p>Thanks in advance.  </p>