【发布时间】:2020-03-24 08:30:21
【问题描述】:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
Student student = new Student();
StudentDB studentDb = new StudentDB();
System.out.println("All Elements from the List \n");
studentDb.getStudentList().forEach(System.out::println);
Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
.collect(Collectors.toMap(student.getName(), student.getActivities()));
}
}
【问题讨论】:
-
您似乎想要
Student::getName和Student::getActivities之类的东西。方法引用,而不是立即调用方法。 -
地图
> studentMap = studentDb.getStudentList().stream() .collect(Collectors.toMap(s -> s.getName(), s -> s.getActivities ()));它工作正常。但是如果我使用方法引用,我会得到编译时错误。地图 > studentMap = studentDb.getStudentList().stream() .collect(Collectors.toMap(student::getName(), student::getActivities())); -
@mmathank 小心,
student::getName和Student::getName(大写 S)不相同
标签: java java-stream type-inference