字典表树状结构最简单的方法

// 1. 获取所有数据List,找到顶级ID
voList.stream().filter( vo ->
                vo.getParentId() == null
        ).map( (menu) -> {
            menu.setHiddenDictVos( getChildrens( menu, voList ) );
            return menu;
        } ).collect( Collectors.toList() );

//2. 把子类塞进去
private List<HiddenDictVo> getChildrens(HiddenDictVo menu, List<HiddenDictVo> voList) {
    return voList.stream().filter( dictVO -> {
        return menu.getDictId().equals(dictVO.getParentId() );
    } ).map( dictVO -> {
        //1、找到子类
        dictVO.setHiddenDictVos( getChildrens( dictVO, voList ) );
        return dictVO;
    } ).collect( Collectors.toList() );
}

// 实体类
public class HiddenDictVo {
    //xxx其他属性略
    private List<HiddenDictVo> hiddenDictVos;
}

// 第二种

public class generateTree{

          List<SysDeptTreeVO> sysDeptTreeVOS = new ArrayList<>();

            for (SysDept root : deptList) {
if (root.getDeptLevel() != null && root.getDeptLevel() == 1) {
SysDeptTreeVO sysDeptTreeVO = getTree(root, deptList);
sysDeptTreeVOS.add(sysDeptTreeVO);
}
}




public static SysDeptTreeVO getTree(SysDept sysDept, List<SysDept> deptList) {
SysDeptTreeVO vo = new SysDeptTreeVO();
BeanUtils.copyProperties(sysDept, vo);
List<SysDeptTreeVO> child = getChild(sysDept, deptList);
vo.setChildrenList(null);
if (child.size() > 0) {
vo.setChildrenList(child);
}
return vo;
}

public static List<SysDeptTreeVO> getChild(SysDept sysDept, List<SysDept> deptList) {
List<SysDeptTreeVO> childList = new ArrayList<>();
for (SysDept root : deptList) {
if (root.getParentId() != null) {
if (root.getParentId().equals(sysDept.getId())) {
SysDeptTreeVO sysDeptTreeVO = getTree(root, deptList);
sysDeptTreeVO.setParentName(sysDept.getDeptName());
childList.add(sysDeptTreeVO);
}
}
}
return childList;
}

}
 
原文地址:https://www.cnblogs.com/padazala/p/15213536.html