将Java 8中的List转换为值为对象列表的Map

huangapple go评论95阅读模式
英文:

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&lt;Entity&gt; entityList;
 Map&lt;String, List&lt;Entity&gt; = entityList.stream()
                                           .collect(Collectors.toMap(Entity::getId,????));

I am having touble populating the value as a List of entity

答案1

得分: 0

你可以直接使用groupingBy收集器与分类函数。以下是它的样子。

Map&lt;String, List&lt;Entity&gt;&gt; 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&lt;String, List&lt;Entity&gt;&gt; entityById = entityList.stream()
	.collect(Collectors.groupingBy(Entity::getId));

huangapple
  • 本文由 发表于 2020年8月4日 00:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63233621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定