简介
api
- 将参数list 构造成 tree getTree(List<Node> list);
源码
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @公司名称:kk51
* @作者:lud —— 2020年9月9日 下午4:01:54
* @说明:tree工具类
*/
public class TreeUtils {
/**
* 方法功能说明:@1.将参数list 构造成 tree
* 创建时间:2020年8月25日 下午3:06:53 --lud
*/
public static List<Node> getTree(List<Node> list) {
Collections.sort(list);
Map<Object, List<Node>> son = list.stream().filter(node -> !"0".equals(node.getParentId()))
.collect(Collectors.groupingBy(node -> node.getParentId()));
list.forEach(node -> node.setChildList(son.get(node.getNodeId())));
return list.stream().filter(node -> "0".equals(node.getParentId())).collect(Collectors.toList());
}
/**
* @公司名称:kk51
* @作者:lud —— 2020年8月25日 下午3:46:44
* @说明:tree节点
*/
public class Node implements Comparable<Node> {
private String nodeId;
private String nodeName;
private String parentId;
private Long sort;
public Long getSort() {
return sort;
}
public void setSort(Long sort) {
this.sort = sort;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Node(String nodeId, String nodeName, String parentId, Long sort) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.parentId = parentId;
this.sort = sort;
}
@Override
public boolean equals(Object obj) {
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
Node other = (Node) obj;
if (nodeId == null) {
if (other.nodeId != null) { return false; }
} else if (!nodeId.equals(other.nodeId)) {
return false;
}
if (nodeName == null) {
if (other.nodeName != null) { return false; }
} else if (!nodeName.equals(other.nodeName)) {
return false;
}
if (parentId == null) {
if (other.parentId != null) { return false; }
} else if (!parentId.equals(other.parentId)) {
return false;
}
if (sort == null) {
if (other.sort != null) { return false; }
} else if (!sort.equals(other.sort)) {
return false;
}
return true;
}
/**
* 下级节点集合
*/
private List<Node> childList;
public List<Node> getChildList() {
return childList;
}
public void setChildList(List<Node> childList) {
this.childList = childList;
}
@Override
public int compareTo(Node node) {
//正序
return this.sort.compareTo(node.sort);
//倒序
// return node.sort.compareTo(this.sort);
}
}
}