我有下面的 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
收集器。 map 的键是员工姓名(假设没有重复项), map 值需要做更多工作。
root.getEmployees().stream().collect(
Collectors.toMap(
Employee::getName,
Employee::getProDataMap
)
}
现在让我们尝试在 Employee
中编写 getProDataMap
。我们再次使用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/