简体   繁体   English

从 Set 初始化 Map

[英]Initialize Map from Set

I have a set of Student - Set<Student> students我有一组学生 - Set<Student> students

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

I am trying to initialize a Map<String,List<StudentResult>> with the entries from set above:我正在尝试使用上面设置的条目初始化Map<String,List<StudentResult>>

Map<String,List<StudentResult>> studentResultMap = students.keySet().stream().collect(
                                                Collectors.toMap(x -> x.getId(),new ArrayList<StudentResult>()));

But this wouldn't compile - how is this to be achieved?但这不会编译 - 这是如何实现的?

new ArrayList<StudentResult>() does not make a correct argument for a Function parameter. new ArrayList<StudentResult>()没有为Function参数提供正确的参数。

You need to use:您需要使用:

x -> new ArrayList<StudentResult>()

Side note: students.keySet() wouldn't compile either, if students is a Set .旁注:如果studentsSet ,那么 student.keySet students.keySet()也不会编译。 You can call stream on it directly:您可以直接在其上调用stream

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

Here lies your problem:你的问题就在这里:

Map<String,List<StudentResult>> studentResultMap = students
    .stream().collect(Collectors.toMap(x -> x.getId(), new ArrayList<StudentResult>()));

You need to pass two functions to Collectors.toMap , but instead, you're passing a List instance as the second parameter您需要将两个函数传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM