这可能是一个简单的 Java 流问题。说,我有一个 List<Student>
对象。
public class Student {
public String name;
public Set<String> subjects;
public Set<String> getSubjects() {
return subjects;
}
}
如何获取学生列表中的所有科目?
我可以使用 for each 循环来做到这一点。如何转换以下代码以使用 Streams?
for (Student student : students) {
subjectsTaken.addAll(student.getSubjects());
}
这是我尝试使用 Java 8 流的尝试。这给了我一个 Incompatible types
错误。
Set<String> subjectsTaken = students.stream()
.map(student -> student.getSubjects())
.collect(Collectors.toSet());
最佳答案
您当前的代码生成一个 Set<Set<String>>
, 不是 Set<String>
.
你应该使用 flatMap
, 不是 map
:
Set<String> subjectsTaken =
students.stream() // Stream<Student>
.flatMap(student -> student.getSubjects().stream()) // Stream<String>
.collect(Collectors.toSet()); // Set<String>
关于java - 如何使用 Java Streams 从对象列表中获取 Set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53816208/