Java的集合List转换成树形结构
采用了人人开源这个项目里面的工具类,非常好用,给我冲冲冲。
下边直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import io.project.common.validator.AssertUtils;
import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
public class TreeUtils {
public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) { AssertUtils.isNull(pid, "pid");
List<T> treeList = new ArrayList<>(); for(T treeNode : treeNodes) { if (pid.equals(treeNode.getPid())) { treeList.add(findChildren(treeNodes, treeNode)); } }
return treeList; }
private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) { for(T treeNode : treeNodes) { if(rootNode.getId().equals(treeNode.getPid())) { rootNode.getChildren().add(findChildren(treeNodes, treeNode)); } } return rootNode; }
public static <T extends TreeNode> List<T> build(List<T> treeNodes) { List<T> result = new ArrayList<>();
Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size()); for(T treeNode : treeNodes){ nodeMap.put(treeNode.getId(), treeNode); }
for(T node : nodeMap.values()) { T parent = nodeMap.get(node.getPid()); if(parent != null && !(node.getId().equals(parent.getId()))){ parent.getChildren().add(node); continue; }
result.add(node); }
return result; }
}
|