JAVA List和Tree互转

list泛型对象中要有pid和当前对象泛型的list Child

public class BgNatureGroup {

    @ApiModelProperty(value = "唯一id", name = "id")
    private String id;

    @ApiModelProperty(value = "父id", name = "sPid")
    private String sPid;

    List<BgNatureGroup> children = new ArrayList<>();

}

 

list转Tree

List<BgNatureGroup> bgNatureGroups = bgNatureGroupDao.selectNatureGroup(param);
List<BgNatureGroup> natureGroupTree = buildValueTree(bgNatureGroups);


/**
     * 构造项目树形结构
     *
     * @param depts
     * @return
     */
    private List<BgNatureGroup> buildValueTree(List<BgNatureGroup> depts) {
        Map<String, BgNatureGroup> entityMap = new HashMap<>();
        List<BgNatureGroup> resultList = new ArrayList<>();

        for (BgNatureGroup entity : depts) {
            entity.setChildren(new ArrayList<>());
            entityMap.put(entity.getId(), entity);
        }

        for (BgNatureGroup entity : depts) {
            BgNatureGroup parentEntity = entityMap.get(entity.getsPid());
            if (StringUtils.isNull(parentEntity)) {
                resultList.add(entity);
                continue;
            }
            parentEntity.getChildren().add(entity);
        }
        for (BgNatureGroup nv:resultList) {
            if(nv.getChildren().size()>0){
                handleChildren(nv.getChildren());
            }
            if(nv.getChildren().size()==0){
                nv.setChildren(null);
            }
        }
        return resultList;
    }



    private void handleChildren(List<BgNatureGroup> d){
        for (BgNatureGroup nv:d) {
            if(nv.getChildren().size()>0){
                handleChildren(nv.getChildren());
            }
            if(nv.getChildren().size()==0){
                nv.setChildren(null);
            }
        }
    }

 

 

Tree转List

传参为Tree的集合

public ResponseBean saveGroupTree(List<BgNatureGroup> list) {
        List<BgNatureGroup> natureGroups = treeToList(list, null);
        return new ResponseBean(true, "操作成功", natureGroups);

    }

/**
     * 树形结构转list
     *
     * @param 
     * @return
     */
    private List<BgNatureGroup> treeToList(List<BgNatureGroup> depts, String pid) {

        List<BgNatureGroup> resultList = new ArrayList<>();

        for (BgNatureGroup ip : depts) {
            ip.setsPid(pid);
            if (ip.getChildren() != null && ip.getChildren().size() > 0) {
                resultList.addAll(treeToList(ip.getChildren(), ip.getId()));
                ip.setChildren(null);
                resultList.add(ip);
            } else {
                resultList.add(ip);
            }
        }
        return resultList;
    }

 

posted @ 2021-10-15 11:03  狴颜丶领衔  阅读(786)  评论(0编辑  收藏  举报