Java 使用流从Json创建嵌套映射
我有下面的Json,我正在读取到具有相同结构的嵌套POJO中Java 使用流从Json创建嵌套映射,java,java-8,java-stream,Java,Java 8,Java Stream,我有下面的Json,我正在读取到具有相同结构的嵌套POJO中 { "employees": [ { "name": "John", "age": "30", "proData": [ { "year": "1", "idLis
{
"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"
]
}
]
}
]
}
现在我想将其映射到如下结构,可以使用idList
中的每个字符串初始化ProData
Map 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);
}
Map finalMap=newhashmap();
对于(员工:root.getEmployees()){
Map proDataMap=new HashMap();
for(ProData ProData:employee.getProData()){
List finalObjs=new ArrayList();
for(字符串id:proData.getIdList()){
添加(新产品数据(id));
}
put(proData.getYear(),finalObjs);
}
finalMap.put(employee.getName(),proDataMap);
}
我想使用流API制作一个更好的版本。最终结果是一个映射,所以使用
toMap
收集器。映射的键是员工姓名(假设没有重复),映射值需要做更多的工作
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())
)
)
}
publicmap getProDataMap(){
返回此.getProData().stream().collect(
汤姆(
ProData::getYear,
proData->proData.getIdList().stream()
.map(ProData::新建)
.collect(收集器.toList())
)
)
}
应该类似于
root.stream().forEach(employee -> {
Map<String,List<ProData>> proDataMap = new HashMap<>();
employee.getProdData().stream().forEach(data -> {
List<ProData> finalObjs = new ArrayList<>();
data.getIdList().stream().forEach(data -> {
finalObjs.add(new ProData(id));
});
});
});
root.stream().forEach(员工->{
Map proDataMap=new HashMap();
employee.getProdData().stream().forEach(数据->{
List finalObjs=new ArrayList();
data.getIdList().stream().forEach(数据->{
添加(新产品数据(id));
});
});
});
但无论如何,您也可以使用Gson来解析它
此链接已满足您的需要,请访问:,停止将StackOverflow视为您的编码器转换应用程序!分享你的尝试,尝试一些失败的东西,然后是ak。谢谢你的详细回复。这正是我所期望的。使用
collection.stream().forEach(…)
比collection.forEach(…)
有什么好处?这不是使用流API的方式。