在开发中经常能遇到需要将带有父子级的数据处理为树形结构数据,网上搜到的基本都是递归,这里不用递归,递归性能太差
@Override
public Map<String, List<Region>> test2() {
Map<String, List<Region>> map = new HashMap<>();
List<Region> regionList = list();
List<Region> emptyList = new ArrayList<>();
// 将数组数据转为map结构,pcode为key
Map<String, List<Region>> regionMap = regionList.stream().map(item -> {
Region region = new Region();
BeanUtils.copyProperties(item, region);
return region;
}).collect(Collectors.groupingBy(Region::getPcode, Collectors.toList()));
// 上面的Collectors.groupingBy将数据按Pcode分组,方便下面操作
// 封装树形结构并塞进emptyList数组中
regionMap.forEach((pcode, collect) -> {
if (pcode.equals("0")) {
emptyList.addAll(collect);
}
collect.forEach(item -> {
item.setChildren(regionMap.get(item.getCode()));
// 因为上面根据pcode分组了,所以这里的collect是以pcode为key的map对象
// ,item则是当前遍历的pcode底下的children
});
});
map.put("tree", emptyList);
return map;
}
处理后的数据格式为
"tree": [
{
"id": 1,
"code": "110000000000",
"name": "北京市",
"pcode": "0",
"pname": "中国",
"abbreviate": "北京",
"type": 1,
"state": true,
"sort": 0,
"children": [
{
"id": 2,
"code": "110100000000",
"name": "市辖区",
"pcode": "110000000000",
"pname": "北京市",
"abbreviate": "北京",
"type": 2,
"state": true,
"sort": 0,
"children": [
{
"id": 3,
"code": "110102000000",
"name": "东城区",
"pcode": "110100000000",
"pname": "市辖区",
"abbreviate": "东城",
"type": 3,
"state": true,
"sort": 0,
"children": null
},
{
"id": 4,
"code": "110101000000",
"name": "西城区",
"pcode": "110100000000",
"pname": "市辖区",
"abbreviate": "西城",
"type": 3,
"state": true,
"sort": 0,
"children": null
},
{
"id": 5,
"code": "110105000000",
"name": "朝阳区",
"pcode": "110100000000",
"pname": "市辖区",
"abbreviate": "朝阳",
"type": 3,
"state": true,
"sort": 0,
"children": null
},
]
}
]
},
{
"id": 19,
"code": "120000000000",
"name": "天津市",
"pcode": "0",
"pname": "中国",
"abbreviate": "天津",
"type": 1,
"state": true,
"sort": 0,
"children": [
{
"id": 20,
"code": "120100000000",
"name": "市辖区",
"pcode": "120000000000",
"pname": "天津市",
"abbreviate": "天津",
"type": 2,
"state": true,
"sort": 0,
"children": [
{
"id": 21,
"code": "120101000000",
"name": "和平区",
"pcode": "120100000000",
"pname": "市辖区",
"abbreviate": "和平",
"type": 3,
"state": true,
"sort": 0,
"children": null
},
{
"id": 22,
"code": "120102000000",
"name": "河东区",
"pcode": "120100000000",
"pname": "市辖区",
"abbreviate": "河东",
"type": 3,
"state": true,
"sort": 0,
"children": null
}
]
}
]
},
]