发现了画图对于理解的帮助了
解决了一直以来困扰我的树状结构问题, 开心
贴上自己的代码
public List<District> getDistricts(String tenant) {
List<District> flatDistricts = mapper.getDistricts(tenant);
//获取孩子键值对
Map<String, List<District>> childGroup = flatDistricts.stream().filter(f -> f.getParentCode() != null).collect(Collectors.groupingBy(District::getParentCode));
//获取所有父元素
List<District> districts = flatDistricts.stream().filter(f->f.getParentCode() == null).collect(Collectors.toList());
ArrayList<District> parents = new ArrayList<>(districts);
for (int i = 0; i < parents.size(); i++) {
District currentParentDistrict = parents.get(i);
List<District> childrenDistricts = childGroup.get(currentParentDistrict.getCode());
if(childrenDistricts != null) {
currentParentDistrict.setChildren(childrenDistricts);
parents.addAll(childrenDistricts);
}
}
return districts;
}