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;
}
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/java/282721.html