title: Java stream collect to map with multiple keys
body: <p>I thought I was getting pretty good at Java 8 streams, but then...</p>
  
  <p>I have a <code>Foo</code> interface:</p>
  
  <pre><code>public interface Foo {
    String getKey();
    Stream&lt;Bar&gt; bars();
  }
  </code></pre>
  
  <p>I know I can collect a <code>Stream&lt;Foo&gt;</code> into a <code>Map&lt;String, Foo&gt;</code> using the key of each:</p>
  
  <pre><code>Map&lt;String, Foo&gt; foosByKey = fooStream.collect(
      Collectors.toMap(Foo::getKey, Function.identity()));
  </code></pre>
  
  <p>But what if I want to collect them into a <code>Map&lt;Bar, Foo&gt;</code>? In other words, for each <code>Foo</code> in the steam, I want to put that <code>Foo</code> in the map keyed to every one of the <code>Bar</code> instances returned by <code>Foo.bars()</code>. Where do I start?</p>