gpt4 book ai didi

java - 需要有关增强 Java 中嵌套 for 循环的建议

转载 作者:行者123 更新时间:2023-11-30 08:43:21 26 4
gpt4 key购买 nike

我的应用程序中有 4 个级别的类别,每个类别都有 7 个子类别。所以它会是一个(7*7*7*7)结构。我需要在服务调用时获取所有四个级别的类别。我的表结构如下,

categoryId, categoryName, parentId, active

因此,对于第一级类别,我根据其 parentId 为 0 来获取,对于其余三个类别级别,我根据其 parentId 对应于 categoryId 来获取。最后,我需要将所有类别的列表返回到域对象中。所以我的抓取代码如下,

 List<DrmCategory> cate1 = categoryRepository.findByParentId(0);
cate1.forEach(category -> {
System.out.println(" Level1 -> Parent ID : "+category.getParentId()+ " Name : "+category.getCategoryName());

List<DrmCategory> cate2 = categoryRepository.findByParentId(category.getCategoryId());
cate2.forEach(category2 ->{
System.out.println(" Level2 -> Parent ID : "+category2.getParentId()+ " Name : "+category2.getCategoryName());

List<DrmCategory> cate3 = categoryRepository.findByParentId(category2.getCategoryId());
cate3.forEach(category3 -> {
System.out.println(" Level3 -> Parent ID : "+category3.getParentId()+ " Name : "+category3.getCategoryName());

List<DrmCategory> cate4 = categoryRepository.findByParentId(category3.getCategoryId());
cate4.forEach(category4 -> {
System.out.println(" Level4 -> Parent ID : "+category4.getParentId()+ " Name : "+category4.getCategoryName());
});
});
}
);
}
);

我觉得上面的代码不是实现功能的最佳方式。任何人都可以提出一些建议来增强嵌套的 for 循环条件。或者,如果有人建议一些更好的设计(表格设计和嵌套循环获取所有级别类别),我将不胜感激。

最佳答案

你可以尝试这样的递归方法:

void recursiveMethod(int currentId, int depth) {

List<DrmCategory> cate = categoryRepository.findByParentId(currentId);
cate.forEach(category -> {
System.out.println(" Level"+depth+" -> Parent ID : "+category.getParentId()+ " Name : "+category.getCategoryName());

if (depth < 4) {
recursiveMethod(category.getCategoryId(), depth + 1);
}
});
}

为了干净起见,您应该根据深度调用另一种方法来管理您的控件。 doSomething(类别, 深度);

要开始递归,请调用 recursiveMethod(0,1);

请注意,这是盲编码,您可能会发现语法错误。

关于java - 需要有关增强 Java 中嵌套 for 循环的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34316859/

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