英文:
Convert a List into a Map with value as a List of Objects in Java 8
问题
我有一个包含重复数据的对象列表。我想将其转换为一个Map,其中键是一个字符串,值是一个实体列表。
List<Entity> entityList;
Map<String, List<Entity>> resultMap = entityList.stream()
.collect(Collectors.groupingBy(Entity::getId));
我在将值填充为实体列表方面遇到了问题。
英文:
I have a List of objects which has duplicate data in it. I would like to convert it into a Map where the key is a String and the value is a List of entities
List<Entity> entityList;
Map<String, List<Entity> = entityList.stream()
.collect(Collectors.toMap(Entity::getId,????));
I am having touble populating the value as a List of entity
答案1
得分: 0
你可以直接使用groupingBy
收集器与分类函数。以下是它的样子。
Map<String, List<Entity>> entityById = entityList.stream()
.collect(Collectors.groupingBy(Entity::getId));
英文:
You can directly use the groupingBy
collector with a classification function. Here's how it looks.
Map<String, List<Entity>> entityById = entityList.stream()
.collect(Collectors.groupingBy(Entity::getId));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论