我们有一张Student map 要记录Map<Student, StudentRecord>
.
学生类如下:
Student {
String id;
String grade;
Int age;
}
此外,我们还有一个学生 ID 列表
(List<String>)
假如。使用 Java 流,过滤出 ID 存在于提供的列表中的学生的记录的最有效方法是什么?
预期结果是映射到 Id(String) 的过滤列表 -
<Map<Id, StudentRecord>>
最佳答案
您可以流式传输一组条目:
map.entrySet().stream()
.filter(e -> list.contains(e.getKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
如果您还想将键映射到
id
字段,然后:map.entrySet().stream()
.filter(e -> list.contains(e.getKey()))
.collect(toMap(e -> e.getKey().getId(), Map.Entry::getValue));
关于java - 与 Map 的键相交的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59551041/