过滤字典并返回键的列表

6

我们有一个Map<String, Student> studentMap,其中Student是以下类:

class Student{
    String name;
    int age;
}

我们需要返回一个所有年龄大于20的eligibleStudents的ID列表。为什么以下代码会在Collectors.toList处出现编译错误?
HashMap<String, Student> studentMap = getStudentMap();
eligibleStudents = studentMap .entrySet().stream()
        .filter(a -> a.getValue().getAge() > 20)
        .collect(Collectors.toList(Entry::getKey));
5个回答

4

toList() 收集器只是创建一个容器来累积元素,不需要任何参数。在收集之前,您需要进行映射。下面是它的样子。

List<String> eligibleStudents = studentMap.entrySet().stream()
    .filter(a -> a.getValue().getAge() > 20)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

4

Collectors.toList() 不带参数,你需要先使用 map 方法:

eligibleStudents = studentMap.entrySet().stream()
    .filter(a -> a.getValue().getAge() > 20)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

0

在使用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());

0

你的解决方案中存在问题,Collectors.toList() 方法不需要任何参数。请参见以下定义。

public static <T> Collector<T,?,List<T>> toList()

filter 操作之后,您将获得 Entry<Id, Student>stream。 因此,您必须将 Entry<Id, Student> 转换为 Id。 在下面的解决方案中进行 map 操作后,您将拥有 Idstream。 然后收集 Ids。

HashMap<String, Student> studentMap = getStudentMap();
List<Id> eligibleStudentIds = studentMap.entrySet().stream()
            .filter(s -> s.getValue().getAge()>20)
            .map(a -> a.getKey())
            .collect(Collectors.toList());

0

我会建议尝试调试终端操作后获取的内容。

在Intellij中有一个功能Alt+Ctrl+V,它会告诉你在操作后左侧得到了什么。

例如

当您拥有以下代码:

studentMap .entrySet().stream()
        .filter(a -> a.getValue().getAge() > 20)
        .collect(Collectors.toList());

当您选择全部并按下 Alt+Ctrl+V 后,您将意识到此代码块返回 List<Map.Entry<String,Integer>>

现在您知道您的返回值不是一个 String 的 List,您现在需要筛选其他内容,仅接受更多的 String,为此您需要使用 map

当您像下面的代码片段一样映射时:

studentMap .entrySet().stream()
                    .filter(a->a.getValue().getAge()>20)
                    .map(a -> a.getKey())
                    .collect(Collectors.toList());

现在,当您选择整个代码片段并按下Alt+Ctrl+V时,您将会发现您现在得到了您之前想要的实际返回值,即List<String>

希望这能在您今后的编码工作中对您有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接