gpt4 book ai didi

java - 使用流从 Json 创建嵌套映射

转载 作者:行者123 更新时间:2023-12-04 08:12:16 24 4
gpt4 key购买 nike

我有下面的 Json,我正在阅读具有相同结构的嵌套 POJO。

{
"employees": [
{
"name": "John",
"age": "30",
"proData": [
{
"year": "1",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "2",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "3",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
}
]
},
{
"name": "Scott",
"age": "32",
"proData": [
{
"year": "1",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "2",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "3",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
}
]
}
]
}
现在我想把它映射到一个像下面这样的结构, ProData可以使用 idList 中的每个字符串进行初始化. Map<String,Map<String,List<ProData>>> finalMap我写了类似下面的东西,它的工作原理。
        Map<String,Map<String,List<ProData>>> finalMap = new HashMap<>();

for(Employee employee:root.getEmployees()){
Map<String,List<ProData>> proDataMap = new HashMap<>();
for(ProData proData: employee.getProData()){
List<ProData> finalObjs = new ArrayList<>();
for(String id:proData.getIdList()){
finalObjs.add(new ProData(id));
}

proDataMap.put(proData.getYear(),finalObjs);
}
finalMap.put(employee.getName(),proDataMap);
}
我想使用流 API 制作更好的版本。

最佳答案

最终结果是一张 map ,所以使用 toMap集电极。映射的键是员工姓名(假设没有重复),映射值需要更多的工作。

root.getEmployees().stream().collect(
Collectors.toMap(
Employee::getName,
Employee::getProDataMap
)
}
现在让我们试着写 getProDataMapEmployee .我们再次使用 toMap集电极。键是年份(假设没有重复),值是映射到 ProData 的 id 列表。使用构造函数。
public Map<String, List<ProData>> getProDataMap() {
return this.getProData().stream().collect(
Collectors.toMap(
ProData::getYear,
proData -> proData.getIdList().stream()
.map(ProData::new)
.collect(Collectors.toList())
)
)
}

关于java - 使用流从 Json 创建嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65896689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com