數(shù)據(jù)結(jié)構(gòu)
{
"productCode":100,
"menuList": [
{
"code": 1001,
"parentCode": null,
"name": "觸達(dá)預(yù)覽",
"sort": 0
},{
"code": 1002,
"parentCode": null,
"name": "營(yíng)銷策略",
"sort": 0
},{
"code": 1003,
"parentCode": null,
"name": "內(nèi)容與資產(chǎn)",
"sort": 0
},{
"code": 2001,
"parentCode": "1001",
"name": "業(yè)務(wù)總覽",
"sort": 0
},
{
"code": 2002,
"parentCode": "1002",
"name": "流程畫布",
"sort": 0
},
{
"code": 3001,
"parentCode": "2002",
"name": "觸達(dá)任務(wù)",
"sort": 1
}
]
}
代碼
private static List<MenuTreeVO> getTree(List<MenuTreeVO> list){
if (ObjectUtil.isEmpty(list)){
return null;
}
//構(gòu)造以菜單CODE為key 對(duì)象為value的map
Map<String,MenuTreeVO> map = list.stream().collect(Collectors.toMap(MenuTreeVO::getCode, item -> item));
//遍歷原list谴蔑,在map中查找,若存在父級(jí)則追加到他的children中
list.stream().filter(o->StrUtil.isNotBlank(o.getParentCode())).forEach(item -> {
Optional.ofNullable(map.get(item.getParentCode()))
.ifPresent(parent -> {
List<MenuTreeVO> children = parent.getChildren();
if (children == null) {
children = new ArrayList<>();
parent.setChildren(children);
}
children.add(item);
});
});
//節(jié)省內(nèi)存占用
map.clear();
//只取出頂級(jí)分類
return list.stream().filter(item -> StrUtil.isBlank(item.getParentCode())).collect(Collectors.toList());
}
結(jié)果測(cè)試
[
{
"id": 1765987779571957761,
"code": "1001",
"parentCode": null,
"name": "觸達(dá)預(yù)覽",
"sort": 0,
"checked": false,
"children": [
{
"id": 1765987779571957764,
"code": "2001",
"parentCode": "1001",
"name": "業(yè)務(wù)總覽",
"sort": 0,
"checked": false,
"children": null
}
]
},
{
"id": 1765987779571957762,
"code": "1002",
"parentCode": null,
"name": "營(yíng)銷策略",
"sort": 0,
"checked": false,
"children": [
{
"id": 1765987779571957765,
"code": "2002",
"parentCode": "1002",
"name": "流程畫布",
"sort": 0,
"checked": false,
"children": [
{
"id": 1765987779571957766,
"code": "3001",
"parentCode": "2002",
"name": "觸達(dá)任務(wù)",
"sort": 1,
"checked": false,
"children": null
}
]
}
]
},
{
"id": 1765987779571957763,
"code": "1003",
"parentCode": null,
"name": "內(nèi)容與資產(chǎn)",
"sort": 0,
"checked": false,
"children": null
}
]