gpt4 book ai didi

java - 在java中创建动态树

转载 作者:行者123 更新时间:2023-12-01 11:04:15 24 4
gpt4 key购买 nike

我需要创建一个基于JSON的动态树数据。我有一个类别列表,每个类别都有一个子类别,其中有一个子类别有一个子类别。

我的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
},
...............
]

主要Categories谁的parentid==0Subcategories ( child )是谁的parentId等于 idCategories 。随后每Subcategory可容纳Child

我需要建一棵树。如果JSON数据返回List<Category>那么最终的树将是这个类 List (即 List<ParentCategory> )

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

如何在 Java 中表示这棵树数据结构?

最佳答案

最简单的方法是通过两次遍历列表:

第 1 步:创建 Map<Integer, ParentCategory>由 id 键控的类别,忽略 ParentCategoryId 和子类别。

Pass2:使用 ParentCategoryId 查找在 Pass1 中创建的 ParentCategory 并将其添加到其子类别

关于java - 在java中创建动态树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33105657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com