title: java create multiple tree like structure using parent id from flat file
body: <p>I have data like below</p>
  
  <pre><code>CategoryId  CategoryName  CategoryParentId
  123         XYZ           111
  111         ABC           
  222         PQR           
  555         DEF           111
  321         IJK           222
  </code></pre>
  
  <p>If you see this a unordered data read from a flat file which can be in any order.</p>
  
  <p>I want to create trees like below:</p>
  
  <pre><code>111
  |  \
  123 555  
  </code></pre>
  
  <p>and</p>
  
  <pre><code>222
  \
  321
  </code></pre>
  
  <p>I have this data in an object, which looks like below:</p>
  
  <pre><code>public class Category {
      private String id = null;
      private String name = null;
      private String parentId = null;
  
      public Category(String id, String name, String parentId) {
          this.id = id;
          this.name = name;
          this.parentId = parentId;
      }
  }
  </code></pre>
  
  <p>I am trying to process this data to create list of categories tree.</p>
  
  <pre><code>public class CategoryTree {
      private String name     = null;
      private String id       = null;
  
      private CategoryTree&lt;String, CategoryTree&gt; children = new TreeMap&lt;String, CategoryTree&gt;();
  
  
      public CategoryTree() {
      }
  
      public CategoryTree(String name, String id) {
          setName(name);
          setId(id);
      }
  
      public TreeMap&lt;String, CategoryTree&gt; getChildren() {
          return this.children;
      }
  
      public CategoryTree getChild(String childId) {
          return this.children.get(childId);
      }
  
      public void setChild(CategoryTree child) {
          this.children.put(child.getId(), child);
      }
  
      public boolean hasChild(String childId) {
          TreeMap&lt;String, CategoryTree&gt; set = this.children;
          boolean result =  set.containsKey(childId);
          return result;
      }
  }
  </code></pre>
  
  <p>Below is what I am trying to do:</p>
  
  <pre><code>public void processData(List categoryList) {
      List&lt;CategoryTree&gt; roleObjectList = new ArrayList&lt;CategoryTree&gt;();
  
      Iterator&lt;Category&gt; itr = categoryList.iterator();
      while (itr.hasNext()) {
          Category entry = itr.next();
          String id = entry.getId();
          String name = entry.getName();
          String parentId = entry.getParentId();
  
          // i am confused here
          // CategoryTree parent = new CategoryTree(name,  id);
             parent.addChild(entry);
      }
  }
  </code></pre>
  
  <p>I am confused on this part. How to start the tree. Since entry in the first iteration of loop has parent but it's parent is not present in the final list yet. How to add first entry to it's parent.</p>