我想使用streams
将一个Student
对象列表转换为Map<Long, List<>>
。
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", "测试1")
键: 3
值列表: Student("3", "测试1"), Student("3", "测试3")
我尝试了以下代码,但它正在重新初始化Student
对象。有人可以帮我修复下面的代码吗?
Map<Long, List<Student>> map = list.stream()
.collect(Collectors.groupingBy(
Student::getId,
Collectors.mapping(Student::new, Collectors.toList())
));