Tree of java objects based on a list of strings representing hierarchy -


i have interesting , understand not easiest task.

i need create tree of objects based on list of strings representing hierarchy.

for example, strings in list (actually graph):

list<string> hierarchies; 

1# 1#2# 1#2#3# 1#2#4# 1#2#4#5#

class have:

class tree {      list<tree> children;      // here getter  } 

i have implementation start. don't know how finish code. can share vision me?

thanks in advance!

tree tree = null;  (string hierarchy : hierarchies) {      if (hierarchy.equals("1#")) {         tree = new tree();     } else {         tree.getchildren().add(new tree());     }  }  return tree; 

there lot of possible solutions. no complexity may like:

public void testhierarchy() {      list<string> hierarchies = new arraylist<string>();      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();     (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;     (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<tree>  children    = new arraylist<sometesttest.tree>();      public list<tree> getchildren() {          return children;     }      public string getvalue() {          return value;     }      public void setvalue(string value) {          this.value = value;     }  } 

p.s. not elegant simple.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -