簡體   English   中英

如何使用Java Streams從對象列表中獲取Set

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

這可能是一個簡單的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>

嘗試這個:

Set<String> subjectsTaken = 
                   students.stream()
                           .map(Student::getSubjects)
                           .flatMap(Set::stream) 
                           .collect(Collectors.toSet());

想法是先將學生映射到他們的主題,然后將Stream<Set<String>>壓平為Stream<String> ,最后將流收集到Set


我建議你使用方法引用而不是lambda表達式 (如果它不會降低可讀性)。

使用Stream<T>#<R>collect另一種選擇:

students.stream()
    .map(Student::getSubjects)
    .<Set<String>>collect(HashSet::new, Collection::addAll, Collection::addAll)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM