java - 将对象列表转换为 Map> 使用流
问题描述
我想将 Student 对象列表转换为Map<Long, List<>>
using streams
.
List<Student> list = new ArrayList<Student>();
list.add(new Student("1", "test 1"));
list.add(new Student("3", "test 1"));
list.add(new Student("3", "test 3"));
我希望通过以下方式获得最终结果:
地图
钥匙:1
价值清单:Student("1", "test 1")
键:3
价值清单:Student("3", "test 1"), Student("3", "test 3")
我尝试了以下代码,但它正在重新初始化Student
对象。谁能帮我修复下面的代码?
Map<Long, List<Student>> map = list.stream()
.collect(Collectors.groupingBy(
Student::getId,
Collectors.mapping(Student::new, Collectors.toList())
));
解决方案
您不需要链接mapping
收集器。默认情况下,单个参数groupingBy
将为您提供一个Map<Long, List<Student>>
。
Map<Long, List<Student>> map =
list.stream()
.collect(Collectors.groupingBy(Student::getId));
推荐阅读
- javascript - FreeCodeCamp:使用 For 循环遍历数组的所有项
- html - 将鼠标悬停在 img 上时表格必须可见
- java - Intellij Spring Boot 运行配置
- ios - SceneView 和 Scene isPlaying, isPaused
- javascript - 如何按数组分组并使用javascript确定总行数
- python-3.x - 使用折线将变量作为参数传递
- javascript - 如何为这个原型创建一个接口?
- r - 用 NA 替换数值
- qt - Azure 上的 Python QT
- r - 如何使用公共颜色条安排多个 ggplot2 grobs?