title: Transform a list of objects into a Map<Parent, List<Descendant>>
body: <p>I have a List of Containers, and each Container can have a single parent Container or no parent Container at all. I want to convert this list into a Map, where the key is the oldest ancestor / parent, and the value is a list of all descendants of that ancestor.</p>
  
  <p>I have tried the following code, which almost works as expected, but it also collects children as parent keys if those children are also parents of other children:</p>
  
  <pre><code>public static void main(String[] args) {
      Container c1 = new Container("c1");
      Container c11 = new Container("c1_1");
      Container c111 = new Container("c1_1_1");
      Container c12 = new Container("c1_2");
      c11.setParent(c1);
      c111.setParent(c11);
      c12.setParent(c1);
  
      Container c2 = new Container("c2");
      Container c21 = new Container("c2_1");
      Container c22 = new Container("c2_2");
      c21.setParent(c2);
      c22.setParent(c2);
  
  
      List&lt;Container&gt; containers = Lists.newArrayList(c1, c11, c111, c12, c2, c21, c22);
  
      System.out.println("All containers: " + containers);
  
      Map&lt;Container, List&lt;Container&gt;&gt; parentsAndChildren = containers.stream()
              .collect(Collectors.groupingBy(container -&gt; container.getParent() == null ? container : container.getParent(), Collectors.mapping(container -&gt; container, Collectors.toList())));
  
      System.out.println("Ancestor / Descendants: " + parentsAndChildren);
  }
  
  @Data
  @RequiredArgsConstructor
  private static final class Container {
      private final String key;
      private Container parent;
  
      public String toString() {
          return key;
      }
  }
  </code></pre>
  
  <p>This results in the following output:</p>
  
  <pre><code>All containers: [c1, c1_1, c1_1_1, c1_2, c2, c2_1, c2_2]
  Ancestor / Descendants: {c1_1=[c1_1_1], c2=[c2, c2_1, c2_2], c1=[c1, c1_1, c1_2]}
  </code></pre>
  
  <p>While the expected output is:</p>
  
  <pre><code>All containers: [c1, c1_1, c1_1_1, c1_2, c2, c2_1, c2_2]
  Ancestor / Descendants: {c2=[c2_1, c2_2], c1=[c1_1, c1_1_1, c1_2]}
  </code></pre>
  
  <p>Note that <code>c1_1_1</code> is a direct descendant of the oldest ancestor <code>c1</code>. Is there a way I can do this easily using Java 8 Stream?</p>