首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用streams将对象列表转换为Map<Long、List<>>

使用streams将对象列表转换为Map<Long、List<>>
EN

Stack Overflow用户
提问于 2021-04-28 13:19:09
回答 5查看 262关注 0票数 8

我想使用streams将学生对象列表转换为Map<Long, List<>>

代码语言:javascript
复制
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对象。有人能帮我修复下面的代码吗?

代码语言:javascript
复制
Map<Long, List<Student>> map = list.stream()
                        .collect(Collectors.groupingBy(
                                Student::getId,
                                Collectors.mapping(Student::new, Collectors.toList())
                        ));
EN

回答 5

Stack Overflow用户

发布于 2021-04-28 13:23:42

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

代码语言:javascript
复制
Map<Long, List<Student>> map = 
    list.stream()
        .collect(Collectors.groupingBy(Student::getId));
票数 13
EN

Stack Overflow用户

发布于 2021-04-28 13:29:24

answer by Eran是非常准确的。除此之外,你还可以使用Supplier,例如

代码语言:javascript
复制
Map<Long, List<Student>> map = 
    list.stream()
        .collect(Collectors.groupingBy(Student::getId, TreeMap::new, Collectors.toList()));
票数 6
EN

Stack Overflow用户

发布于 2021-04-29 04:45:44

对于这些简单的用例,我更喜欢使用Eclipse Collections,而不是依赖于创建Stream的开销。

结果是一样的,它提供了一个java.util.Map,我发现它的语法更简洁

代码语言:javascript
复制
MutableList<Student> list = Lists.mutable.of();
list.add(new Student("1", "test 1"));
list.add(new Student("3", "test 1"));
list.add(new Student("3", "test 3"));

Map<String, List<Student>> map = list.groupBy(Student::getId).toMap(ArrayList::new);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67294152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档