java 实现字符串转换为树

2022/8/29 1:22:52

本文主要是介绍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
            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;
        }
    }

}



这篇关于java 实现字符串转换为树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程