【发布时间】:2020-01-31 05:10:39
【问题描述】:
FamilyLegacy
ParentList<Parent>
Parent //(Obj Class)
ParentId // String ID
ChildList<Child> // List
Child
ChildId
GrandChildList<GrandChild>
GrandChild
GrandChildId
// Some GrandChild attribs
{
"parents": [
{
"Id": "P1",
"parentName": "BigBob",
"Child": [
{
"id": "C1",
"name": "BOB",
"grandChild": [
{
"grandChildId": "G1",
"grandChildName": "John"
},
{
"grandChildId": "G2",
"grandChildName": "Doe"
}
]
},
{
"id": "C2",
"name": "Marley",
"grandChild": [
{
"grandChildId": "G3",
"grandChildName": "Katty"
},
{
"grandChildId": "G4",
"grandChildName": "Perry"
}
]
}
]
}
]
}
输出到 ->
{
"P1": {
"name": "BigBob",
"C1": {
"name": "Bob",
"G1": {
"name": "John"
},
"G2": {
"name": "Doe"
}
},
"C2": {
"name": "Marey",
"G3": {
"name": "Katty"
},
"G4": {
"name": "Parry"
}
}
}
}
考虑上面的嵌套对象列表结构。有没有办法将此结构转换为嵌套 Map,例如
Map<String,Map<String, Map<String,Map<String,GrandChild>>>>
ParentId -> map of Parents ->map of childs ->map of grand childs keyed with respective IDs
例如一级映射
Map<String, Parent> parentMap =
FamilyLegacy.getParents().stream().collect(
Collectors.toMap(Parent::getParentId,Function.identity()));
我很难可视化映射和嵌套,如果有一种方法可以使用直接分组或映射而不是迭代单个列表对象,我将不胜感激
【问题讨论】:
-
你能提供一个可重现的例子吗?
-
添加了一个Json示例来可视化数据结构。
-
说真的,这个数据结构太复杂了。考虑创建一个实用程序类。一个
NestedMap4<K1, K2, K3, K4, V>可能。或者,由于这是关于 JSON,请考虑创建与您的结构匹配的 POJO,然后使用 GSON 将其读入。
标签: java list dictionary java-8 java-stream