我们有一个Map<String, Student> studentMap
,其中Student
是一个类,如下所示:
class Student{
String name;
int age;
}
我们需要返回所有 Id 的列表 eligibleStudents
,其中年龄 > 20。
为什么下面会在 Collectors.toList
处给出编译错误:
HashMap<String, Student> studentMap = getStudentMap();
eligibleStudents = studentMap .entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.collect(Collectors.toList(Entry::getKey));
最佳答案
Collectors.toList()
不接受任何参数,您需要先映射
它:
eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
关于java - 过滤映射并返回键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59298247/