使用streams将student对象列表转换为map< long,list< >>

xpszyzbs  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(287)

我想将学生对象列表转换为 Map<Long, List<>> 使用 streams ```
List list = new ArrayList();
list.add(new Student("1", "test 1"));
list.add(new Student("3", "test 1"));
list.add(new Student("3", "test 3"));

我希望最终结果如下
Map
键:1值列表: `Student("1", "test 1")` 键:3值列表: `Student("3", "test 1"),Student("3", "test 3")` 我尝试了以下代码,但它正在重新初始化student对象。有人能帮我修复下面的代码吗?

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

lyfkaqu1

lyfkaqu11#

你不需要锁链 mapping 收藏家。单一论点 groupingBy 会给你一个 Map<Long, List<Student>> 默认情况下。

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

mftmpeh82#

伊兰的答案是正确的。除此之外,您还可以使用 Supplier 例如

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

相关问题