你好,我有一个类别列表:
public class Category{
private Integer id;
private Integer parentId;
}
如何获取给定父母的所有后代/孩子的列表?
例如:
1 : 2
1 : 3
2 : 4
我得到1、2、3、4
答案 0 :(得分:1)
您可以使用这种简单的方法(可能效率不高),该方法使用递归尝试
public List<Integer> getChildrenIds(Integer parentId, List<Category> categories){
Set<Integer> knownParents = new HashSet<>();
List<Integer> result = new LinkedList<>();
for(Category category : categories){
// if category has the parent we're looking for
if(category.parentId.equals(parentId)){
// then add it to our result
result.add(category.id);
// this check is used to get all the children recursivly
// but should be done only once, which is why we are using an intermediate set
if(!knownParents.contains(category.id)){
knownParents.add(category.id);
result.addAll(getChildrenIds(category.id, categories));
}
}
}
return result;
}
可以这样称呼:
List<Integer> childrenIds = getChildrenIds(1, categories);
当数据不一致时,这会以StackOverflowError
中断。
例如当具有2个类别时,彼此引用:
Category(id: 1, parentId: 2)
Category(id: 2, parentId: 1)
答案 1 :(得分:0)
您可以遍历所有类别的列表,并检查给定ID的 direct 个子代,请参见以下示例:
public class MainCategoryChecker {
public static void main(String[] args) {
// create some categories and put them in a List
List<Category> categories = new ArrayList<Category>();
Category one = new Category(1, 0); // the root category has parent id = 0
categories.add(one);
Category two = new Category(2, 1);
categories.add(two);
Category three = new Category(3, 1);
categories.add(three);
Category four = new Category(4, 2);
categories.add(four);
printSubCategories(1, categories);
}
public static void printSubCategories(int parentId, List<Category> categories) {
for (Category c : categories) {
if (c.getParentId() == parentId) {
System.out.println(parentId + " : " + c.getId());
}
}
}
}