将对象列表转换为Map< Long,List>>.使用流 [英] Convert a list of objects to Map<Long, List<>> using streams

查看:56
本文介绍了将对象列表转换为Map< Long,List>>.使用流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 streams 将Student对象的列表转换为 Map< Long,List<>> .

I want to convert a list of Student objects to 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"));

我希望通过以下方式获得最终结果:

I want the final outcome in the following way:

地图

键:1

值列表: Student("1","test 1")

键:3

值列表:学生("3",测试1"),学生("3",测试3")

我尝试了以下代码,但是它正在重新初始化 Student 对象.谁能帮我修复以下代码?

I tried the following code, but it is reinitializing the Student objects. Can anyone help me fix the below code?

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

推荐答案

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

You don't need to chain the mapping collector. The single argument groupingBy will give you a Map<Long, List<Student>> by default.

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

这篇关于将对象列表转换为Map&lt; Long,List&gt;&gt;.使用流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆