java 实现字符串转换为树


import java.util.*;

class Node {
    
    public static void main(String[] args) {
        ArrayList<String> listOfPaths = new ArrayList<String>();
        listOfPaths.add("主要材料|钢铁|锌铜板");
        listOfPaths.add("主要材料|通风口|cc");
        listOfPaths.add("主要材料|压路机");
        listOfPaths.add("主要材料|加药装置");
        listOfPaths.add("主要材料|加药装置1");
        listOfPaths.add("主要材料|钢铁");
        listOfPaths.add("主要材料|钢铁|锌铜板1");
        listOfPaths.add("工程设备|钢铁|锌铜板");

        TreeMap structure = new TreeMap<>();
        for (String path : listOfPaths) {
            String[] tmp = path.split("\\|", 2); // [ "folder a/", "folder b/file 1"]  for first loops step
            String way = "";
            put(structure, tmp[0], tmp[1], way);
        }
        List<Material> materials = new ArrayList<>();
        print(structure, "", materials);

        System.out.println(Arrays.toString(materials.toArray()));
    }

    private static void put(TreeMap structure, String root, String rest, String way) {
        String[] tmp = rest.split("\\|", 2);

        TreeMap rootDir = (TreeMap) structure.get(root);

        if (rootDir == null) {
            rootDir = new TreeMap();
            structure.put(root, rootDir);
        }
        if (tmp.length == 1) { // path end
            TreeMap child = (TreeMap)rootDir.get(tmp[0]);
            if (!tmp[0].equals("") && child == null) rootDir.put(tmp[0], null);
        } else {
            put(rootDir, tmp[0], tmp[1], way);
        }
    }

    private static void print(TreeMap map, String way, List<Material> materials) {
        if (map == null || map.isEmpty())
            return;
        String o = way;
        for (Object m : map.entrySet()) {
            Material material = new Material();
            material.setName((String) ((Map.Entry) m).getKey());
            material.setChildren(new ArrayList<>());
            if (Objects.equals(way, "")) {
                way = (String) ((Map.Entry) m).getKey();
            } else {
                way += "|" + (String) ((Map.Entry) m).getKey();
            }
            material.setWay(way);
            materials.add(material);
            print((TreeMap) ((Map.Entry) m).getValue(), way, material.getChildren());
            way = o;
        }
    }

}

posted @ 2022-08-28 20:48  简单易懂  阅读(362)  评论(0编辑  收藏  举报