我有以下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制作更好的版本。
最终结果是一张地图,因此请使用toMap
收集器。地图的键是员工姓名(假设没有重复),并且地图值需要更多的工作。
root.getEmployees().stream().collect(
Collectors.toMap(
Employee::getName,
Employee::getProDataMap
)
}
现在,让我们试着写getProDataMap
在Employee
。再次,我们使用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())
)
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句