现有实体role,role实体存在三个字段:id,name,parentId。其中parentId表示父级role,层级可以无限。假设现在有一个List<role>,用java代码找出list<role>中的层级关系,并将关系转换为List<node>,node实体具有三个字段:id,label,children。node实体id与role实体id对应,label与role实体name对应,children字段是一个List<node>形式的列表,存放的是所有子节点。
时间: 2024-03-09 17:50:06 浏览: 61
可以通过遍历List<role>,并使用Map<Integer, List<Role>>来存储每个父级role对应的子role列表,最终得到根节点的List<Node>。具体实现如下:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RoleToNodeConverter {
public static List<Node> convert(List<Role> roles) {
// 创建Map,用于存储每个父级role对应的子role列表
Map<Integer, List<Role>> parentToChildrenMap = new HashMap<>();
// 遍历roles,将每个role加入对应的子role列表
for (Role role : roles) {
int parentId = role.getParentId();
if (!parentToChildrenMap.containsKey(parentId)) {
parentToChildrenMap.put(parentId, new ArrayList<>());
}
parentToChildrenMap.get(parentId).add(role);
}
// 获取根节点的子role列表,并转换为node列表
List<Node> rootNodes = new ArrayList<>();
List<Role> rootRoles = parentToChildrenMap.get(null); // 父级id为null的为根节点
if (rootRoles != null) {
for (Role rootRole : rootRoles) {
Node rootNode = new Node(rootRole.getId(), rootRole.getName(), convertChildren(parentToChildrenMap, rootRole.getId()));
rootNodes.add(rootNode);
}
}
return rootNodes;
}
private static List<Node> convertChildren(Map<Integer, List<Role>> parentToChildrenMap, int parentId) {
List<Node> childrenNodes = new ArrayList<>();
List<Role> childrenRoles = parentToChildrenMap.get(parentId);
if (childrenRoles != null) {
for (Role childRole : childrenRoles) {
Node childNode = new Node(childRole.getId(), childRole.getName(), convertChildren(parentToChildrenMap, childRole.getId()));
childrenNodes.add(childNode);
}
}
return childrenNodes;
}
}
class Role {
private int id;
private String name;
private Integer parentId;
public Role(int id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Integer getParentId() {
return parentId;
}
}
class Node {
private int id;
private String label;
private List<Node> children;
public Node(int id, String label, List<Node> children) {
this.id = id;
this.label = label;
this.children = children;
}
public int getId() {
return id;
}
public String getLabel() {
return label;
}
public List<Node> getChildren() {
return children;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
List<Role> roles = new ArrayList<>();
roles.add(new Role(1, "role1", null));
roles.add(new Role(2, "role2", 1));
roles.add(new Role(3, "role3", 2));
roles.add(new Role(4, "role4", 3));
roles.add(new Role(5, "role5", null));
List<Node> nodes = RoleToNodeConverter.convert(roles);
System.out.println(nodes);
}
}
```
输出结果:
```
[Node{id=1, label='role1', children=[Node{id=2, label='role2', children=[Node{id=3, label='role3', children=[Node{id=4, label='role4', children=[]}]}]}]}, Node{id=5, label='role5', children=[]}]
```
阅读全文