生成树工具包

需求:解决生成树形结构问题

一开始是遍历sql得到效果图,但是如果数据量较大的话对服务器压力较大,并且耗时长,优化在代码中写出树工具类

  • 数据库表结构:
area_idarea_namefarth_id
101xxx
105w101

得到最终效果图:

在这里插入图片描述

java代码:

	SELECT
    	area_id id,
    	area_name title,
   	    fath_id fathId
    FROM dim_areas
	public class TreeUtil {

    public static <T extends BaseTreeGrid> List<T> formatTreeInList(List<T> paramList) {
        List<T> resultTree = new ArrayList<>();
        List<T> childrenNotes = new ArrayList<>();
        for (T t : paramList) {
            if (StringUtils.isBlank(t.getFathId())) {
                resultTree.add(t);
            } else {
                childrenNotes.add(t);
            }
        }

        for (T fathNote : resultTree) {
            List<T> resultGrid = getTreeChildrens(fathNote.getId(), childrenNotes);
            fathNote.setChildrens(resultGrid);
            fathNote.setFathId("");
        }
        return resultTree;
    }

    public static <T extends BaseTreeGrid> List<T> getTreeChildrens(String id, List<T> baseTreeGrids) {
        List<T> resultTreeGrids = new ArrayList<T>();
        for (T t:baseTreeGrids) {
            if (id.equals(t.getFathId())) {
                List<T> children = getTreeChildrens(t.getId(), baseTreeGrids);
                t.setChild(children);
                resultTreeGrids.add(t);
            }
        }
        return resultTreeGrids;
    }


public class BaseTreeGrid implements Serializable {

    private String id;

    private String title;

    private String fathId;

    private List<?> childrens;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值