> 使用流,java,java-8,java-stream"/>

首页 > 解决方案 > 将对象列表转换为 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())
                        ));

标签: javajava-8java-stream

解决方案


您不需要链接mapping收集器。默认情况下,单个参数groupingBy将为您提供一个Map<Long, List<Student>>

Map<Long, List<Student>> map = 
    list.stream()
        .collect(Collectors.groupingBy(Student::getId));

推荐阅读