java list转tree (递归方式)

2021-10-20  本文已影响0人  zt_sole

实体

菜单list 实体

@Data
public class MenuVO implements Serializable {
    /**
     * 菜单id
     */
    private Long id;
   
    /**
     * 菜单名称
     */
    private String name;
    /**
     * 菜单编码
     */
    private String code;
   
    /**
     * 父节点ID
     */
    private Long parentId;
    /**
     * 菜单类型
     */
    private Integer type;
    /**
     * 描述
     */
    private String description;
    /**
     * 次序
     */
    private Integer sequence;

菜单树实体

@Data
@EqualsAndHashCode(callSuper = false)
public class MenuTreeVO extends MenuVO {
    List<MenuTreeVO> children;
}

方法

    /**
     *  list 转 tree
     * @param pId 父级id,list 数据中最顶级的父级id。
     * @param list list
     * @return
     */
    public static List<MenuTreeVO> listToTree(Long pId, List<Menu> list) {
        List<MenuTreeVO> ret = new ArrayList<>();
        if (null == list) {
            return ret;
        }
               Iterator<Menu> iterable = list.iterator();
        while (iterable.hasNext()) {
            Menu menu = iterable.next();
            if (menu.getParentId().equals(pId)) {
                MenuTreeVO pMenu = new MenuTreeVO();

                pMenu.setId(menu.getId());
                pMenu.setName(menu.getName());
                pMenu.setCode(menu.getCode());
                pMenu.setParentId(menu.getParentId());
                pMenu.setType(menu.getType());
                pMenu.setDescription(menu.getDescription());
                pMenu.setSequence(menu.getSequence());
 if (iterator.hasNext()) {
                    iterator.remove();
                }
                List<MenuTreeVO> children = listToTree(menu.getId(), list);
                pMenu.setChildren(children);
                ret.add(pMenu);
                //iterable.remove();
            }

        }
        return ret;
    }


上一篇下一篇

猜你喜欢

热点阅读