List转换成 tree

这篇博客介绍了两种在Java中将列表数据转换为树形结构的方法。第一种方法是自定义了一个`TreeUtils`工具类,通过递归处理实现了将具有id和parentId字段的对象列表转换成`TreeNode`对象的树结构。另一种方法是利用Hutool库的`TreeUtil`,通过指定父节点ID和配置,快速构建树形结构。示例代码展示了如何使用这两种方法。
摘要由CSDN通过智能技术生成

``java
**
第一种方式:

首先声明一个工具类

**

public class TreeUtils {
public TreeUtils() {
}

public static <T> List<T> toTree(List<T> List, Class<T> clazz) {
    return toTree(List, (String)null, (String)null, (String)null, clazz);
}

public static List<TreeNode> toTree(List<? extends TreeNode> List) {
    return toTree(List, (int)0);
}

public static List<TreeNode> toTree(List<? extends TreeNode> List, Object rootNodeId) {
    List<TreeNode> roots = new ArrayList();
    Iterator var3 = List.iterator();

    TreeNode root;
    while(var3.hasNext()) {
        root = (TreeNode)var3.next();
        Object parentId = root.getParentId();
        if (isRootNode(parentId, rootNodeId)) {
            roots.add(root);
        }
    }

    List.removeAll(roots);
    var3 = roots.iterator();

    while(var3.hasNext()) {
        root = (TreeNode)var3.next();
        addChild(root, List);
    }

    Collections.sort(roots, (o1, o2) -> {
        Integer o1Sort = (Integer)Optional.ofNullable(o1.getSort()).orElse(0);
        Integer o2Sort = (Integer)Optional.ofNullable(o2.getSort()).orElse(0);
        return o2Sort - o1Sort;
    });
    return roots;
}

private static void addChild(TreeNode node, List<? extends TreeNode> List) {
    Object id = node.getId();
    List<TreeNode> children = node.getChildren();
    if (null == children) {
        children = new ArrayList();
    }

    Iterator var4 = List.iterator();

    while(var4.hasNext()) {
        TreeNode t = (TreeNode)var4.next();
        Object o = t.getParentId().toString();
        if (id.toString().equals(o)) {
            ((List)children).add(t);
            node.setChildren((List)children);
            addChild(t, List);
        }
    }

}

public static <T> List<T> toTree(List<T> List, String id, String parent, String children, Class<T> clazz) {
    try {
        if (List != null && !List.isEmpty()) {
            if (StringUtils.isEmpty(id)) {
                id = "id";
            }

            if (StringUtils.isEmpty(parent)) {
                parent = "parent";
            }

            if (StringUtils.isEmpty(children)) {
                children = "children";
            }

            ArrayList roots = new ArrayList();

            Field idField;
            try {
                idField = clazz.getDeclaredField(id);
            } catch (NoSuchFieldException var14) {
                idField = clazz.getSuperclass().getDeclaredField(id);
            }

            Field parentField;
            try {
                parentField = clazz.getDeclaredField(parent);
            } catch (NoSuchFieldException var13) {
                parentField = clazz.getSuperclass().getDeclaredField(parent);
            }

            Field childrenField;
            try {
                childrenField = clazz.getDeclaredField(children);
            } catch (NoSuchFieldException var12) {
                childrenField = clazz.getSuperclass().getDeclaredField(children);
            }

            idField.setAccessible(true);
            parentField.setAccessible(true);
            childrenField.setAccessible(true);
            Iterator var9 = List.iterator();

            Object root;
            while(var9.hasNext()) {
                root = var9.next();
                Object parentId = parentField.get(root);
                if (isRootNode(parentId, 0)) {
                    roots.add(root);
                }
            }

            List.removeAll(roots);
            var9 = roots.iterator();

            while(var9.hasNext()) {
                root = var9.next();
                addChild(root, List, idField, parentField, childrenField);
            }

            idField.setAccessible(false);
            parentField.setAccessible(false);
            childrenField.setAccessible(false);
            return roots;
        } else {
            return null;
        }
    } catch (Exception var15) {
        throw new RuntimeException(var15);
    }
}

private static <T> void addChild(T node, List<T> List, Field idField, Field parentField, Field childrenField) throws IllegalAccessException {
    Object id = idField.get(node);
    List<T> children = (List)childrenField.get(node);
    if (children == null) {
        children = new ArrayList();
    }

    Iterator var7 = List.iterator();

    while(var7.hasNext()) {
        T t = var7.next();
        Object o = parentField.get(t);
        if (id.equals(o)) {
            ((List)children).add(t);
            childrenField.set(node, children);
            addChild(t, List, idField, parentField, childrenField);
        }
    }

}

private static boolean isRootNode(Object parentId, Object rootNodeId) {
    boolean flag = false;
    if (parentId == null) {
        flag = true;
    } else if (!(parentId instanceof String) || !StringUtils.isEmpty(parentId) && !parentId.equals(rootNodeId.toString())) {
        if (parentId instanceof Integer && rootNodeId.equals(parentId)) {
            flag = true;
        }
    } else {
        flag = true;
    }

    return flag;
}

}

实体类继承基础类

public class Model extends TreeNode implements java.io.Serializable {
String name ;

}
public class TreeNode{
private Long id;
private String name;
private String title;
private Boolean expand = false;
private Serializable parentId;
private Integer sort;
private List children;

public List<TreeNode> getChildren() {
    if (!CollectionUtils.isEmpty(this.children)) {
        Collections.sort(this.children, (o1, o2) -> {
            Integer o1Sort = (Integer)Optional.ofNullable(o1.getSort()).orElse(0);
            Integer o2Sort = (Integer)Optional.ofNullable(o2.getSort()).orElse(0);
            return o2Sort - o1Sort;
        });
    }

    return this.children;
}

public void setChildren(List<TreeNode> children) {
    this.children = children;
}

public String getTitle() {
    this.title = this.getName();
    return this.title;
}

public TreeNode() {
}

public Long getId() {
    return this.id;
}

public String getName() {
    return this.name;
}

public Boolean getExpand() {
    return this.expand;
}

public Serializable getParentId() {
    return this.parentId;
}

public Integer getSort() {
    return this.sort;
}

public void setId(final Long id) {
    this.id = id;
}

public void setName(final String name) {
    this.name = name;
}

public void setTitle(final String title) {
    this.title = title;
}

public void setExpand(final Boolean expand) {
    this.expand = expand;
}

public void setParentId(final Serializable parentId) {
    this.parentId = parentId;
}

public void setSort(final Integer sort) {
    this.sort = sort;
}

public String toString() {
    return "TreeNode(id=" + this.getId() + ", name=" + this.getName() + ", title=" + this.getTitle() + ", expand=" + this.getExpand() + ", parentId=" + this.getParentId() + ", sort=" + this.getSort() + ", children=" + this.getChildren() + ")";
}

public boolean equals(final Object o) {
    if (o == this) {
        return true;
    } else if (!(o instanceof TreeNode)) {
        return false;
    } else {
        TreeNode other = (TreeNode)o;
        if (!other.canEqual(this)) {
            return false;
        } else {
            label95: {
                Object this$id = this.getId();
                Object other$id = other.getId();
                if (this$id == null) {
                    if (other$id == null) {
                        break label95;
                    }
                } else if (this$id.equals(other$id)) {
                    break label95;
                }

                return false;
            }

            Object this$name = this.getName();
            Object other$name = other.getName();
            if (this$name == null) {
                if (other$name != null) {
                    return false;
                }
            } else if (!this$name.equals(other$name)) {
                return false;
            }

            Object this$title = this.getTitle();
            Object other$title = other.getTitle();
            if (this$title == null) {
                if (other$title != null) {
                    return false;
                }
            } else if (!this$title.equals(other$title)) {
                return false;
            }

            label74: {
                Object this$expand = this.getExpand();
                Object other$expand = other.getExpand();
                if (this$expand == null) {
                    if (other$expand == null) {
                        break label74;
                    }
                } else if (this$expand.equals(other$expand)) {
                    break label74;
                }

                return false;
            }

            label67: {
                Object this$parentId = this.getParentId();
                Object other$parentId = other.getParentId();
                if (this$parentId == null) {
                    if (other$parentId == null) {
                        break label67;
                    }
                } else if (this$parentId.equals(other$parentId)) {
                    break label67;
                }

                return false;
            }

            Object this$sort = this.getSort();
            Object other$sort = other.getSort();
            if (this$sort == null) {
                if (other$sort != null) {
                    return false;
                }
            } else if (!this$sort.equals(other$sort)) {
                return false;
            }

            Object this$children = this.getChildren();
            Object other$children = other.getChildren();
            if (this$children == null) {
                if (other$children != null) {
                    return false;
                }
            } else if (!this$children.equals(other$children)) {
                return false;
            }

            return true;
        }
    }
}

protected boolean canEqual(final Object other) {
    return other instanceof TreeNode;
}

public int hashCode() {
    int PRIME = true;
    int result = 1;
    Object $id = this.getId();
    int result = result * 59 + ($id == null ? 43 : $id.hashCode());
    Object $name = this.getName();
    result = result * 59 + ($name == null ? 43 : $name.hashCode());
    Object $title = this.getTitle();
    result = result * 59 + ($title == null ? 43 : $title.hashCode());
    Object $expand = this.getExpand();
    result = result * 59 + ($expand == null ? 43 : $expand.hashCode());
    Object $parentId = this.getParentId();
    result = result * 59 + ($parentId == null ? 43 : $parentId.hashCode());
    Object $sort = this.getSort();
    result = result * 59 + ($sort == null ? 43 : $sort.hashCode());
    Object $children = this.getChildren();
    result = result * 59 + ($children == null ? 43 : $children.hashCode());
    return result;
}

}

**

如果有id 、parentId,可直接调用

**
例如:

TreeUtils.toTree(sysResourceList)

**

如果没有parentId,可重命名直接调用

**

例如:

TreeUtils.toTree(dappReviews, “id”, “dappReviewsId”, “children”, MktDappReview.class);

第二种方式:

引入hutool依赖

	<dependency>
		<groupId>cn.hutool</groupId>
		<artifactId>hutool-all</artifactId>
		<version>5.8.1</version>
	</dependency>

调用:
//list数据集合
List bdBzhReviews = bdBzhReviewService.selectBdBzhReviewList(bdBzhReview);
//组装树结构
List<Tree> build = TreeUtil.build(bdBzhReviews, “0”, new TreeNodeConfig(),
(treeNode, tree) -> {
tree.setId(treeNode.getId().toString());
tree.setParentId(treeNode.getParentId().toString());
tree.setWeight(treeNode.getNumber());
tree.setName(treeNode.getName());
tree.put(“type”, treeNode.getType());
tree.put(“label”,treeNode.getName());
tree.put(“rank”,treeNode.getRank() + “,” + treeNode.getId());
});





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值