递归查询子级元素,返回树形菜单数据

 

    /**
     * 将普通的entity的集合转成存在树状结构的集合
     * @param list
     * @return
     */
    public static List<CityVo> getDtoTreeList(List<DvCity> list){
        List<CityVo> dtos = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return dtos;
        }
        for (DvCity city : list) {
            if (city.getParentCode()==0){
                //找到顶层目录
                CityVo cityVo = new CityVo();
                //将实体类的数据转成dto
                BeanUtil.copyProperties(city,cityVo);
                cityVo.setName(city.getName());
                //获取该实体类下的所有子级
                dtos.add(findChildren(cityVo,list));
            }
        }
        return dtos;
    }

    /**
     * 获取cityVo类下面的所有子级,存到dto中的children中
     * @param cityVo
     * @param list
     * @return
     */
    private static CityVo findChildren(CityVo cityVo, List<DvCity> list) {
        for (DvCity city : list) {
            if (cityVo.getCode().equals(city.getParentCode())){
                //此时menu是menuDto下的子级
                if (cityVo.getChildList() == null){
                    cityVo.setChildList(new ArrayList<CityVo>());
                }
                CityVo dto = new CityVo();
                BeanUtil.copyProperties(city,dto);
                dto.setName(city.getName());
                //递归
                cityVo.getChildList().add(findChildren(dto,list));
            }
        }
        return cityVo;
    }

  实体类

@Data
  @Accessors(chain = true)
@ApiModel(value="DvCity对象", description="城市表")
public class DvCity extends BaseObject {

    private static final long serialVersionUID=1L;

      @ApiModelProperty(value = "城市编码")
      @Id
      private Integer code;

      @ApiModelProperty(value = "城市名称")
      private String name;

      @ApiModelProperty(value = "父级code")
      private Integer parentCode;

      @ApiModelProperty(value = "是否显示 0显示1不显示")
      private Integer deleted;
}

  

 

posted @ 2021-05-24 14:46  valar-dohaeris  阅读(179)  评论(0编辑  收藏  举报