java 查询树_java 获取树形结构数据

将一个平行的list转换成树形的list:

import java.io.Serializable;

import java.util.ArrayList;

import java.util.List;

public class Node implements Serializable {

private String path;

private String component;

private Long id;

private String name;

private String redirect;

/**

* 是否为叶子节点

*/

private boolean leaf;

private boolean menuShow;

private Long parentId;

private String iconCls;

List children;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getPath() {

return path;

}

public void setPath(String path) {

this.path = path;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getComponent() {

return component;

}

public void setComponent(String component) {

this.component = component;

}

public String getRedirect() {

return redirect;

}

public void setRedirect(String redirect) {

this.redirect = redirect;

}

public boolean getLeaf() {

return leaf;

}

public void setLeaf(boolean leaf) {

this.leaf = leaf;

}

public boolean getMenuShow() {

return menuShow;

}

public void setMenuShow(boolean menuShow) {

this.menuShow = menuShow;

}

public Long getParentId() {

return parentId;

}

public void setParentId(Long parentId) {

this.parentId = parentId;

}

public boolean isLeaf() {

return leaf;

}

public String getIconCls() {

return iconCls;

}

public void setIconCls(String iconCls) {

this.iconCls = iconCls;

}

public List getChildren() {

return children;

}

public void setChildren(List children) {

this.children = children;

}

public static List buildToTree(List nodes) {

if (nodes == null) {

return null;

}

List topNodes = new ArrayList();

for (Node child : nodes) {

Long pid = child.getParentId();

if (pid == null || 0l == pid) {

topNodes.add(child);

continue;

}

for (Node parent : nodes) {

Long id = parent.getId();

if (id != null && id.equals(pid)) {

parent.getChildren().add(child);

continue;

}

}

}

return topNodes;

}

}


版权声明:本文为weixin_39829501原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。