title: Creating a Map using Java8 streams on a nested Data Structure
body: <p>I am searching for an elegant equivalent of this piece of code using Java 8's streams:</p>
  
  <pre class="lang-java prettyprint-override"><code>Collection&lt;X&gt; xs = ...;
  Map&lt;B, A&gt; map = new SomeMap&lt;&gt;();
  
  for (X x : xs) {
      A a = x.getA();
      Collection&lt;B&gt; bs = x.getBs();
  
      for (B b : bs)
          map.put(b, a);
  }
  </code></pre>
  
  <p>That one is a bit too tricky for me as I can’t think of a combination using flatMap and Collectors.toMap which would implement the desired functionality.</p>
  
  <p>Compilable example:</p>
  
  <pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Map;
  
  public class Application {
  
      public static class A {}
  
      public static class B {}
  
      public static class X {
          private A a;
          private Collection&lt;B&gt; bs;
  
          public X(A a, Collection&lt;B&gt; bs) {
              this.a = a;
              this.bs = bs;
          }
  
          public A getA() {
              return a;
          }
  
          public Collection&lt;B&gt; getBs() {
              return bs;
          }
      }
  
      public static void main(String[] args) {
          X x1 = new X(new A(), Arrays.asList(new B(), new B()));
          X x2 = new X(new A(), Arrays.asList(new B()));
  
          Collection&lt;X&gt; xs = Arrays.asList(x1, x2);
  
          Map&lt;B, A&gt; map = new HashMap&lt;&gt;();
  
          for (X x : xs) {
              A a = x.getA();
              Collection&lt;B&gt; bs = x.getBs();
  
              for (B b : bs)
                  map.put(b, a);
          }
      }
  
  }
  </code></pre>