How to get all nested articles for a specific category?

Help
2013-12-14
2013-12-17
  • I want to get all nested articles for a specific category, contains "getChildArticles" for the current and all nested child categories. I'm playing with the following function:
    private Set<String> getChildCategories(Category cat)
    {
    Set<String> childs = new HashSet<>();
    Queue<Category> q = new PriorityQueue<>();
    q.add(cat);
    while(!q.isEmpty())
    {
    Category c = q.poll();
    childs.add(c.getTitle());
    for(Category child: c.getChildCategories())
    {
    if(childs.contains(child.getTitle()) || child.getGenerality() > c.getGenerality() ||
    isNoisy(child.getTitle()))
    continue;
    q.add(child);
    }
    }
    return childs;
    }
    I know that categories maybe contains loop. So I'm trying to escape from loops by saving all processed categories. Unfortunately the above code leads to infinity loop in the while body.

     
  • David Milne
    David Milne
    2013-12-17

    Hi Amir,

    It looks like you are performing a breadth first search:

    http://en.wikipedia.org/wiki/Breadth-first_search

    A simple way to avoid loops is to keep a big HashSet of the category ids you have seen.
    If you see a category a second time, you know that you do not need to visit any of its children.