从Set初始化Map

3

我有一个学生集合 - Set<Student> students

class Student{
    String Id;
    String getId(){ return Id;} 
.....
}

我正在尝试使用上述set中的条目初始化一个Map<String,List<StudentResult>>
Map<String,List<StudentResult>> studentResultMap = students.keySet().stream().collect(
                                                Collectors.toMap(x -> x.getId(),new ArrayList<StudentResult>()));

但是这段代码无法编译 - 如何实现?
2个回答

4

new ArrayList<StudentResult>()不能用作Function参数。

你需要使用:

x -> new ArrayList<StudentResult>()

顺便提一下:students.keySet()如果studentsSet类型也无法通过编译。你可以直接在其上调用stream方法:

students.stream().collect(Collectors.toMap(x -> x.getId(), 
                                           a -> new ArrayList<>()));

3

以下是您的问题:

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>()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接