我需要根据父子关系将数据列表转换为列表列表。如果 parent 为 null 落入一级,则二级将基于一级 id。
我的数据如下所示:
[
{id:1, parent: null },
{id:2, parent: 1 },
{id:3, parent: 1 },
{id:4, parent: 1 },
{id:5, parent: 2 },
{id:6, parent: 2 },
{id:7, parent: 3 },
{id:8, parent: 3 },
{id:9, parent: 4 },
{id:10, parent: 4 },
{id:11, parent: 5 },
{id:12, parent: null },
{id:13, parent: 12 },
]
我的代码是:
响应数据
Map<String,Map<String,ResponseData>> map = new HashMap<>();
for (ResponseData responseData : responseDataList) {
Map<String,responseData> responseDatasMap = map.get(responseData.getParent());
if(responseDatasMap != null) {
responseDatasMap.put(responseData.getId(),responseData);
map.put(responseData.getParent(),responseDatasMap);
} else {
responseDatasMap = new HashMap<>();
responseDatasMap.put(responseData.getParent(),responseData);
map.put(responseData.getParent(),responseDatasMap);
}
}
上面的地图将包含父级作为键和映射到父级的值的地图
List<List<ResponseData>> sections = new ArrayList<>();
for (Map.Entry<String,Map<String, ResponseData>> responseDataMap : map.entrySet()) {
Map<String, ResponseData> valueMap = responseDataMap.getValue();
responseDataList = new ArrayList<>();
for(Map.Entry<String, ResponseData> responseData :valueMap.entrySet()) {
responseDataList.add(responseData.getValue());
}
sections.add(responseDataList);
}
我的输出如下所示:
[
[ {id:1, parent: null } ],
[ {id:2, parent: 1 },{id:3, parent: 1 },{id:4, parent: 1 } ],
[ {id:5, parent: 2 },{id:6, parent: 2 } ],
[ {id:7, parent: 3 },{id:8, parent: 3 } ],
[ {id:9, parent: 4 },{id:10, parent: 4 } ],
[ {id:11, parent: 5 }]
]
请检查并让我知道我们如何实施。提前致谢
PIPIONE
相关分类