我们有一个Map<String, Student> studentMap
,其中Student
是一个类,如下所示:
class Student{
String name;
int age;
}
我们需要返回所有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));
发布于 2019-12-11 21:34:59
Collectors.toList()
不带任何论点,您需要首先对其进行map
:
eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
发布于 2019-12-11 21:34:58
toList()
收集器只创建一个容器来积累元素,并且不接受参数。您需要在收集映射之前进行映射。这是看上去的样子。
List<String> eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
发布于 2019-12-11 21:56:30
在filter
之后,您将得到一个类型为Student
的流。对于过滤流中的每个学生,您需要他/她的年龄。所以,你必须对一个学生和他/她的年龄进行一对一的映射。为此,请使用map
运算符如下:
HashMap<String, Student> studentMap = getStudentMap();
eligibleStudents = studentMap .entrySet().stream()
.filter(a->a.getValue().getAge()>20)
.map(a -> a.getKey())
.collect(Collectors.toList());
https://stackoverflow.com/questions/59298247
复制