我想使用streams将学生对象列表转换为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", "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())
));发布于 2021-04-28 13:23:42
您不需要链接mapping收集器。默认情况下,单个参数groupingBy将为您提供一个Map<Long, List<Student>>。
Map<Long, List<Student>> map =
list.stream()
.collect(Collectors.groupingBy(Student::getId));发布于 2021-04-28 13:29:24
answer by Eran是非常准确的。除此之外,你还可以使用Supplier,例如
Map<Long, List<Student>> map =
list.stream()
.collect(Collectors.groupingBy(Student::getId, TreeMap::new, Collectors.toList()));发布于 2021-04-29 04:45:44
对于这些简单的用例,我更喜欢使用Eclipse Collections,而不是依赖于创建Stream的开销。
结果是一样的,它提供了一个java.util.Map,我发现它的语法更简洁
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);https://stackoverflow.com/questions/67294152
复制相似问题