gpt4 book ai didi

java - 过滤映射并返回键列表

转载 作者:行者123 更新时间:2023-12-02 07:45:20 25 4
gpt4 key购买 nike

我们有一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com