import java.util.List; /** * 节点类继承接口,节点类必须继承此类 * */ public interface Treeable<T> { /** * 获取存入map key * @return */ Object getMapKey(); /** * 获取孩子节点的key值 * @return */ Object getChildrenKey(); /** * 根节点key值 * @return */ Object getRootKey(); /** * 子节点赋值 * @param children */ void setChildren(List<T> children); } /** * ListToTree 一个函数式接口 */ import java.util.List; public interface ListToTree<T extends Treeable> { /** * list转化tree结构 */ List<T> toTree(List<T> list); } import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * */ public class ListToTreeImpl implements ListToTree { @Override public List toTree(List list) { // TODO list 空判断,做处理 Map<Object, List> map = new HashMap<Object, List>(); Object rootKye = null; for(Object o : list) { Treeable t = (Treeable) o; Object key = t.getMapKey(); if(map.containsKey(key)) { map.get(key).add(o); } else { List mapValue = new ArrayList(); mapValue.add(o); map.put(key, mapValue); } // 获取根节点key值 if(rootKye == null) { rootKye = t.getRootKey(); } } List tree = map.get(rootKye); recursionToTree(tree, map); return tree; } private void recursionToTree(List list, Map<Object, List> map){ // TODO list 空判断,做处理 for(Object o : list){ Treeable t = (Treeable) o; Object key = t.getChildrenKey(); if(map.containsKey(key)) { List children = map.get(key); t.setChildren(children); recursionToTree(children, map); } } } } import lombok.Data; import java.util.List; /** * */ @Data public class TreeNode implements Treeable { private Integer id; private Integer pid; private String name; private List<TreeNode> children; public TreeNode() { } public TreeNode(Integer id, Integer pid, String name) { this.id = id; this.pid = pid; this.name = name; } @Override public Integer getMapKey() { return pid; } @Override public Integer getChildrenKey() { return id; } @Override public Integer getRootKey() { return 0; } @Override public void setChildren(List children) { this.children = children; } } import java.util.ArrayList; import java.util.List; /** * */ public class Demo { public static void main(String[] args) { /** * 初始化一个list数据,pid=0为根节点 */ List<TreeNode> list = new ArrayList<TreeNode>(); list.add(new TreeNode(1, 0, "1")); list.add(new TreeNode(2, 0, "2")); list.add(new TreeNode(3, 2, "3")); list.add(new TreeNode(4, 3, "4")); list.add(new TreeNode(5, 4, "5")); list.add(new TreeNode(6, 5, "6")); ListToTree treeBuilder = new ListToTreeImpl(); List<TreeNode> tree = treeBuilder.toTree(list); System.out.println(tree); } }