英文:
Combine list of list into map using stream
问题
import java.util.*;
import java.util.stream.Collectors;
class Pojo {
String type;
List<String> ids;
}
public class Main {
public static void main(String[] args) {
List<Pojo> pojoList = new ArrayList<>();
// Add your Pojo objects to the list
Map<String, List<String>> resultMap = pojoList.stream()
.flatMap(pojo -> pojo.ids.stream().map(id -> new AbstractMap.SimpleEntry<>(id, pojo.type)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
System.out.println(resultMap);
}
}
This code uses Java streams to achieve the desired conversion. Replace the comment with your actual list of Pojo objects. The code processes each Pojo object, extracts the type and ids, and then creates pairs of id-type mappings. These pairs are collected into a map where the keys are the ids and the values are lists of associated types.
英文:
I'm trying to convert a pojo object that looks like
[
{
"type": "Preferred",
"ids": ["A", "B", "C"]
},
{
"type": "Non-preferred",
"ids": ["D", "E"]
},
{
"type": "Popular",
"ids": ["A", "D"]
}
]
into Map<String, List<String>>
, such as:
{
"A": ["Preferred", "Popular"],
"B": ["Preferred"],
"C": ["Preferred"],
"D": ["Non-preferred", "Popular"],
"E": ["Non-preferred"],
}
how can I accomplish this using stream? I preferably want to utilize stream into collect()
, instead of using forEach()
(which is basically a for-loop).
Thanks in advance.
EDIT:
The pojo class looks something like:
class Pojo {
String type;
List<String> ids;
}
And I basically have List<Pojo>
答案1
得分: 0
你可以使用流(stream)来实现,为每种类型和ID组合创建条目,然后进行分组操作。
Map<String, List<String>> results = lists.stream()
.flatMap(obj -> obj.getIds()
.stream()
.map(id -> new AbstractMap.SimpleEntry<>(id, obj.getType())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
英文:
You can do it using stream, create entry for each type and id combination and then do a group by
Map<String, List<String>> results = lists.stream()
.flatMap(obj->obj.getIds()
.stream()
.map(id->new AbstractMap.SimpleEntry<>(id,obj.getType())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,Collectors.toList())));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论