Mysql数据:
代码如下:
Entity:
@Data
@Accessors(chain = true)
public class Region {
private BigInteger id;
//名称
private String name;
//父id
private BigInteger parentId;
private List<Region> children;
private Integer createTime;
private Integer updateTime;
private Integer isDeleted;
}
Service核心代码:
List<Region> reginaList = regionMapper.findReginaList();
//将数据以父类ID分组成map:{1:[xxx,xxx],2:[xxx,xxxx]}
Map<BigInteger, List<Region>> parentIdMap = reginaList.stream().collect(Collectors.groupingBy(Region::getParentId, Collectors.toList()));
//循环每个数据,从父类MAP中通过他的ID获取他的子类塞到children中
reginaList.forEach(region -> addChildren(region, parentIdMap));
//只筛选出最顶级数据
List<Region> regions =
reginaList.stream().filter(regina -> regina.getParentId().compareTo(BigInteger.ZERO) == 0).collect(Collectors.toList());
private void addChildren(Region region, Map<BigInteger, List<Region>> parentIdMap) {
List<Region> regions = parentIdMap.get(region.getId());
if (regions != null) {
region.setChildren(regions);
regions.forEach(child -> addChildren(child, parentIdMap)); // 递归添加子级的子级
}
}
第二种写法:
reginaList.stream().filter(city-> city.getParentId().compareTo(BigInteger.ZERO) == 0).peek(city -> city.setCityNames(getChildren(city,reginaList)))
.collect(Collectors.toList());
public List<Region> getChildren(Region region, List<Region> regionList) {
List<Region> childrens = regionList.stream().filter(re -> re.getParentId().compareTo(region.getId()) == 0)
.map(childRegion -> {
childRegion.setAddressNames(getChildren(childRegion, regionList));
return childRegion;
}).collect(Collectors.toList());
return childrens;
}