使用流使用另一个列表中的值填充地图的值

问题描述 投票:0回答:1

鉴于我有一个Map<String, List<Student>>类型的映射和一个List<Student>类型的列表。如何使用流使用List<Student>中的元素填充地图的列表值(最初是空列表)?

字符串键应该是一门课程(例如数学或英语),每个学生都有一个包含所有课程的集合。我想将每门课程用作地图中的键,其值是所有参加该课程的学生的列表。

这是我的代码:

studentMap.entrySet().stream()
.map(entry -> entry.getValue()).
collect(studentList.stream().map(student -> student.getClasses() //Returns a set of that student's courses));

我的代码不起作用,因为我不知道如何从地图的课程键中获取一组学生的课程。

java java-8 stream
1个回答
0
投票

如果您的要求是仅添加到现有的Map而不创建新的KVS,则可以尝试这样的操作:

Map<String, List<Student>> map = new HashMap<>();
students.stream()
            .flatMap(student -> student.getClasses().stream().map(classname -> new AbstractMap.SimpleEntry<>(classname, student)))
            .forEach(entry -> map.computeIfPresent(entry.getKey(), (s, students1) -> students1).add(entry.getValue()));

但是它混合了“流”和“迭代”方法,并且修改了在流之外的Map,这使其具有副作用。

如果您想直接将List转换为新的Map,则可以使用:

Map<String, List<Student>> myMap = students.stream()
            .flatMap(student -> student.getClasses().stream().map(classname -> new AbstractMap.SimpleEntry<>(classname, student)))
            .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
© www.soinside.com 2019 - 2024. All rights reserved.