title: Stream - Nested Collection - Convert to Map
body: <p>Let's say i have 2 classes.</p>
  
  <p><strong>Course Class</strong></p>
  
  <pre><code>public class Course {
      private int id;
      private String name;
  }
  </code></pre>
  
  <p><strong>Student Class</strong></p>
  
  <pre><code>public class Student {
      private int id;
      private String name;
      private List&lt;Course&gt; courses;
  }
  </code></pre>
  
  <p>I have <code>List&lt;Student&gt;</code> and each <code>Student</code> is enrolled in multiple courses.</p>
  
  <p>I need to filter out results using Java 8 stream API's as following.</p>
  
  <pre><code>Map&lt;courseId, List&lt;Student&gt;&gt; 
  </code></pre>
  
  <p>I have tried below, but no success:</p>
  
  <p><strong>1st Approach</strong>        </p>
  
  <pre><code>Map&lt;Integer, List&lt;Student&gt;&gt; courseStudentMap = studentList.stream()
      .collect(Collectors.groupingBy(
          student -&gt; student.getCourses().stream()
              .collect(Collectors.groupingBy(Course::getId))));
  </code></pre>
  
  <p><strong>2nd Approach</strong></p>
  
  <pre><code>Map&lt;Integer, List&lt;Student&gt;&gt; courseStudentMap = studentList.stream()
      .filter(student -&gt; student.getCourses().stream()
          .collect(Collectors.groupingBy(
              Course::getId, Collectors.mapping(Student::student, Collectors.toList()))));
  </code></pre>