有很多可能的解决方案。没有复杂性,它可能看起来像:
public void testHierarchy() {
List hierarchies = new ArrayList();
hierarchies.add("1#");
hierarchies.add("1#2#");
hierarchies.add("1#2#3#");
hierarchies.add("1#2#4#");
hierarchies.add("1#2#4#5#");
Tree root = new Tree();
for (String hierarchy : hierarchies) {
String[] elHierarchy = hierarchy.split("#");
processLevel(elHierarchy, root);
}
}
private void processLevel(String[] hierarchy, Tree rootTree) {
if (null == rootTree.getValue() || "".equals(rootTree.getValue())) {
rootTree.setValue(hierarchy[0]);
}
Tree nextChild = null;
for (Tree child : rootTree.getChildren()) {
if (child.getValue().equals(hierarchy[1])) {
nextChild = child;
break;
}
}
if (hierarchy.length > 1) {
if (null == nextChild) {
nextChild = new Tree();
nextChild.setValue(hierarchy[1]);
rootTree.getChildren().add(nextChild);
}
String[] remainHierarchy = new String[hierarchy.length - 1];
System.arraycopy(hierarchy, 1, remainHierarchy, 0, remainHierarchy.length);
processLevel(remainHierarchy, nextChild);
}
}
private static class Tree {
String value;
List children = new ArrayList();
public List getChildren() {
return children;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
P.S。不是太优雅而是简单。