[英]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.