这篇文章主要讲解了“Java中list转树的应用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java中list转树的应用”吧!
public class TreeNode { private String id; private String parentId; private String name; private List<TreeNode> children; public TreeNode(String id, String name, String parentId) { this.id = id; this.parentId = parentId; this.name = name; } public TreeNode(String id, String name, TreeNode parent) { this.id = id; this.parentId = parent.getId(); this.name = name; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<TreeNode> getChildren() { return children; } public void setChildren(List<TreeNode> children) { this.children = children; } @Override public String toString() { return "TreeNode{" + "id='" + id + '\'' + ", parentId='" + parentId + '\'' + ", name='" + name + '\'' + ", children=" + children + '}'; } } public class TreeBuilder { /** * 两层循环实现建树 * @param treeNodes 传入的树节点列表 * @return */ public static List<TreeNode> bulid(List<TreeNode> treeNodes) { List<TreeNode> trees = new ArrayList<TreeNode>(); for (TreeNode treeNode : treeNodes) { if ("0".equals(treeNode.getParentId())) { trees.add(treeNode); } for (TreeNode it : treeNodes) { if (it.getParentId() == treeNode.getId()) { if (treeNode.getChildren() == null) { treeNode.setChildren(new ArrayList<TreeNode>()); } treeNode.getChildren().add(it); } } } return trees; } }
感谢各位的阅读,以上就是“Java中list转树的应用”的内容了,经过本文的学习后,相信大家对Java中list转树的应用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。