How to get a Set from a list of objects using Java Streams

SyncMaster :

This might be a simple Java streams question. Say, I have a List<Student> object.

public class Student {
    public String name;
    public Set<String> subjects;

    public Set<String> getSubjects() {
        return subjects;
    }
}

How can I get all the subjects taken by the list of students?

I can do this using a for each loop. How can I convert the below code to use Streams?

for (Student student : students) {
    subjectsTaken.addAll(student.getSubjects());
}

Here is my attempt at using Java 8 streams. This gives me an Incompatible types error.

Set<String> subjectsTaken = students.stream()
        .map(student -> student.getSubjects())
        .collect(Collectors.toSet());
Eran :

Your current code produces a Set<Set<String>>, not a Set<String>.

You should use flatMap, not map:

Set<String> subjectsTaken = 
    students.stream() // Stream<Student>
           .flatMap(student -> student.getSubjects().stream()) // Stream<String>
           .collect(Collectors.toSet()); // Set<String>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73341&siteId=1