[英]Create a dynamic tree in java
I need to create a dynamic tree based on JSON
data. 我需要基于
JSON
数据创建动态树。 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: 我的
JSON
数据示例是:
[
{
"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 id
s of Categories
. 主要
Categories
,其parentid==0
和Subcategories
(孩子)是他们parentId
是eqaual到id
号第Categories
。 Subsequently every Subcategory
can hold Child
. 随后,每个
Subcategory
都可以容纳Child
。
I need to build a tree. 我需要盖一棵树。 If
JSON
Data returns List<Category>
then final tree will be this class List
(ie List<ParentCategory>
) 如果
JSON
数据返回List<Category>
则最终的树将是此类List
(即List<ParentCategory>
)
public class ParentCategory {
Category category;
List<ParentCategory> Subcategories;
}
How can I represent this tree in Java
data structures? 如何在
Java
数据结构中表示这棵树?
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. Pass1:创建一个由
Map<Integer, ParentCategory>
id Map<Integer, ParentCategory>
键键入类别的Map<Integer, ParentCategory>
,而忽略ParentCategoryId和Subcategories。
Pass2: Use the ParentCategoryId to lookup up the ParentCategory created in Pass1 and add to it's Subcategories Pass2:使用ParentCategoryId查找在Pass1中创建的ParentCategory,并将其添加到其子类别中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.