ashraful
ashraful

Reputation: 2271

Create a dynamic tree in java

I need to create a dynamic tree based on JSON data. I have a list of categories, every category has a child subcategory which has a subcategory which has a child.

My JSON data example is:

    [
      {
        "Id": 110,
        "Name": "Winter Collection",
        "ParentCategoryId": 0,
        "Description": null,
        "DisplayOrder": 0
      },
      {
        "Id": 111,
        "Name": "Hoodies",
        "ParentCategoryId": 110,
        "Description": null,
        "DisplayOrder": 0
      },
      {
        "Id": 113,
        "Name": "Pullover/Sweater",
        "ParentCategoryId": 110,
        "Description": null,
        "DisplayOrder": 0
      }
{
    "Id": 116,
    "Name": "Jacket \u0026 Blazer",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 118,
    "Name": "Sweatshirts",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 119,
    "Name": "Winter Accessories",
    "ParentCategoryId": 110,
    "Description": null,
    "DisplayOrder": 2
  },
  {
    "Id": 23,
    "Name": "Men\u0027s T-Shirt",
    "ParentCategoryId": 0,
    "Description": null,
    "DisplayOrder": 1
  },
  {
    "Id": 24,
    "Name": "Men\u0027s T-Shirt (Full sleeve)",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": -1
  },
  {
    "Id": 79,
    "Name": "Black T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 80,
    "Name": "White T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 81,
    "Name": "Red T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
  {
    "Id": 82,
    "Name": "Blue T-Shirt",
    "ParentCategoryId": 23,
    "Description": null,
    "DisplayOrder": 0
  },
    ...............
    ] 

Main Categories whose parentid==0 and Subcategories (children) are whose parentId are eqaual to ids of Categories. Subsequently every Subcategory can hold Child.

I need to build a tree. If JSON Data returns List<Category> then final tree will be this class List(i.e List<ParentCategory>)

public class ParentCategory {
   Category category;
   List<ParentCategory> Subcategories;
}

How can I represent this tree in Java data structures?

Upvotes: 0

Views: 308

Answers (1)

lance-java
lance-java

Reputation: 27958

Easiest way is to run through the list with two passes:

Pass1: Create a Map<Integer, ParentCategory> of the categories keyed by id, ignoring ParentCategoryId and Subcategories.

Pass2: Use the ParentCategoryId to lookup up the ParentCategory created in Pass1 and add to it's Subcategories

Upvotes: 1

Related Questions