![](/img/trans.png)
[英]How to iterate and get the object from list of object which contains another list of list of object using lambdas or stream
[英]Get element from list that contains another list
我用java有這個配置:
Student {
private List<Note> notes;
}
Note {
private int value;
// Constructor - getters - setters
}
School {
Private List<Student> students;
// Constructor - getters - setters
}
我想要以下行為:
學生們 :
S1 : note1(value=10), note2(value=16)
S2 : note1(value=7), note2(value=18), note3(value=2)
S3 : note1(value=19)
我想管理一個帶有學校列表的對象:
Manage {
private List<School> schools;
}
我想找到擁有更高音符的學生的學校。
在這個例子中:結果將是 S3,因為我們有一個學生的高音符 19。
如何使用 Java Stream 實現此行為?
您可以創建所有School
和Student
對的Stream<Map.Entry<School,Student>>
,然后找到具有最大值的Student
的條目。
為此,我建議向Student
類添加一個getMaxValue()
方法,該方法將返回所有Student
的Note
的最大值。
Optional<School> school =
schools.stream()
.flatMap(sc -> sc.getStudents()
.stream()
.map(st -> new SimpleEntry<>(sc,st)))
.collect(Collectors.maxBy(Comparator.comparing(e -> e.getValue().getMaxValue())))
.map(Map.Entry::getKey);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.