[英]Initialize Map from Set
我有一組學生 - Set<Student> students
class Student{
String Id;
String getId(){ return Id;}
.....
}
我正在嘗試使用上面設置的條目初始化Map<String,List<StudentResult>>
:
Map<String,List<StudentResult>> studentResultMap = students.keySet().stream().collect(
Collectors.toMap(x -> x.getId(),new ArrayList<StudentResult>()));
但這不會編譯 - 這是如何實現的?
new ArrayList<StudentResult>()
沒有為Function
參數提供正確的參數。
您需要使用:
x -> new ArrayList<StudentResult>()
旁注:如果students
是Set
,那么 student.keySet students.keySet()
也不會編譯。 您可以直接在其上調用stream
:
students.stream().collect(Collectors.toMap(x -> x.getId(),
a -> new ArrayList<>()));
你的問題就在這里:
Map<String,List<StudentResult>> studentResultMap = students
.stream().collect(Collectors.toMap(x -> x.getId(), new ArrayList<StudentResult>()));
您需要將兩個函數傳遞給Collectors.toMap
,但相反,您將List
實例作為第二個參數傳遞
Map<String,List<StudentResult>> studentResultMap = students
.stream().collect(Collectors.toMap(x -> x.getId(), x -> new ArrayList<StudentResult>()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.