Construct a tree structure from list of string paths

后端 未结 6 792
名媛妹妹
名媛妹妹 2020-11-29 01:03

I have a collection of string paths like [\"x1/x2/x3\",\"x1/x2/x4\",\"x1/x5\"] in a list. I need to construct a tree-like structure from this list which can be iterated to g

6条回答
  •  悲哀的现实
    2020-11-29 01:22

    This is way how I am doing tree from path (folders) structure. Maybe should help someone with basic logic.

    Node:

    public class Node {
        private String path;
        private List children;
    
        public Node(String path) {
            this.path = path;
            children = new ArrayList<>();
        }
    
        public String getName() {
            return getName(path);
        }
    
        private String getName(String path) {
            String[] split = path.split("\\\\");
            return split[split.length - 1];
        }
    
        public void addChild(Node child) {
            children.add(child);
        }
    
        public List getChildren() {
            return children;
        }
    
        public String getPath() {
            return path;
        }
    }
    

    FilesTree:

    public class FilesTree {
        private static final Logger log = Logger.getLogger(FilesTree.class.getName());
    
        private FilesTree() {}
    
        private static void createTree(Node root, List paths) {
            for (String path : paths) {
                addNode(root, Arrays.asList(path.split("\\\\")), "");
            }
        }
    
        private static void addNode(Node node, List path, String nodePath) {
            if (!path.isEmpty()) {
                nodePath = nodePath.equals("") ? path.get(0) : String.format("%s\\%s", nodePath, path.get(0));
            }
    
            if (node.getChildren().isEmpty() && path.size() == 1) {
                node.addChild(new Node(nodePath));
            } else if (!node.getChildren().isEmpty()) {
                for (Node actual : node.getChildren()) {
                    if (actual.getName().equals(path.get(0))) {
                        addNode(actual, path.subList(1, path.size()), nodePath);
                        return;
                    }
                }
                node.addChild(new Node(nodePath));
            } else {
                log.info("Without children but with size: " + path.size());
            }
        }
    }
    

提交回复
热议问题