title: How to get a Set from a list of objects using Java Streams
body: <p>This might be a simple Java streams question. Say, I have a <code>List&lt;Student&gt;</code> object.</p>
  
  <pre><code>public class Student {
      public String name;
      public Set&lt;String&gt; subjects;
  
      public Set&lt;String&gt; getSubjects() {
          return subjects;
      }
  }
  </code></pre>
  
  <p>How can I get all the subjects taken by the list of students? </p>
  
  <p>I can do this using a for each loop. How can I convert the below code to use Streams?</p>
  
  <pre><code>for (Student student : students) {
      subjectsTaken.addAll(student.getSubjects());
  }
  </code></pre>
  
  <p>Here is my attempt at using Java 8 streams. This gives me an <code>Incompatible types</code> error.</p>
  
  <pre><code>Set&lt;String&gt; subjectsTaken = students.stream()
          .map(student -&gt; student.getSubjects())
          .collect(Collectors.toSet());
  </code></pre>