渲染树型结构

package com.cbb.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Component;

/**
 *@Data
 *@NoArgsConstructor
 *@AllArgsConstructor
 *@TableName("item")
 * public class Item {
 *    @TableId(value = "eid", type = IdType.AUTO)
 *    private Integer eid;
 *    @TableField("name")
 *    private String name;
 *    @TableField("parent_id")
 *    private Integer parentId;
 *    @TableField(exist = false)
 *    private List<Item> chirldren;
 *}

 * @author 陈斌斌
 * @Date 2022年9月11日 15点44分
 *
 */

@Component
public class Tree {
    /**
     * 构建前端所需要树结构
     *
     * @param trees 列表
     * @return 树结构列表
     */
    public static List<Item> buildDeptTree(List<Item> trees) {
        List<Item> returnList = new ArrayList<Item>();
        List<Integer> tempList = new ArrayList<Integer>();
        for (Item dept : trees) {
            tempList.add(dept.getEid());
        }
        for (Iterator<Item> iterator = trees.iterator(); iterator.hasNext();) {
            Item Item = (Item) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(Item.getParentId())) {
                recursionFn(trees, Item);
                returnList.add(Item);
            }
        }
        if (returnList.isEmpty()) {
            returnList = trees;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private static void recursionFn(List<Item> list, Item t) {
        // 得到子节点列表
        List<Item> childList = getChildList(list, t);
        t.setChirldren(childList);
        for (Item tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private static List<Item> getChildList(List<Item> list, Item t) {
        List<Item> tlist = new ArrayList<Item>();
        for (Item n : list) {
            if (n.getParentId() != null && n.getParentId().longValue() == t.getEid().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<Item> list, Item t) {
        return getChildList(list, t).size() > 0;
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值