IUn*_*own 6 java dictionary list java-8 java-stream
我们有一个Map<String, Student> studentMap,其中Student是一个类,如下所示:
class Student{
String name;
int age;
}
Run Code Online (Sandbox Code Playgroud)
我们需要返回一个包含所有 Ids 的列表eligibleStudents,其中年龄 > 20。
为什么下面会在 处给出编译错误Collectors.toList:
HashMap<String, Student> studentMap = getStudentMap();
eligibleStudents = studentMap .entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.collect(Collectors.toList(Entry::getKey));
Run Code Online (Sandbox Code Playgroud)
Collectors.toList()不接受任何论点,您map首先需要:
eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)