2016-09-19 27 views
1

我有ListNodes其中包含嵌套列表child nodes。我试图遍历所有这些节点以找到特定的节点。目前,我从root级别开始child nodes,然后使用for-each循环进行一级深度到sub child node等等。 这是我的代码:迭代期间交换集合

List<Node> children = root.getChildren(); 
    boolean found = false; 

    while (!found) { 

     for (Node node : children) { 

      if (!node.getData().toString().toUpperCase().contains("BRANCH")) { 
       if(condition){//some processing} 
       } else { 
        //swap children with sub children 
        if (children.get(0) != null) { 
         children = children.get(0).getChildren(); // this operation is not possible during iteration 
        } 
       } 
      } else { 
       continue; 
      } 
     } 

    } 

} 

如果child node没有找到任何匹配,那么我需要sub child node交换收集和不断迭代等。 有没有更好的方法来遍历儿童的嵌套nodelist

+0

这似乎是一个XY问题。我会建议递归,但不清楚你实际正在做什么。 –

+0

@JornVernee:我试图从arraylist构建java层次结构树,然后转换为json(gson)在网页中呈现。 –

回答

1

除了交换集合之外,还可以将元素添加到队列中,并不断迭代,直到队列为空(即没有找到匹配项)为止。或者你确实找到一场比赛并提前回归。

public static void algorithm(Node root) { 
    Queue<Node> q = new LinkedList<>(); 
    q.add(root); 

    while(!q.isEmpty()) { 
     Node current = q.poll(); 

     if(current .getData().toString().toUpperCase().contains("BRANCH")) { 
      continue; 
     } 

     if(condition){ 
      //some processing 
      return; 
     } else { 
      q.addAll(current.getChildren()); 
     } 
    } 
} 
algorithm(root); 
+0

这正是我想要的。工作完美。谢谢! –

0

你不能像这个中间迭代那样交换。记住,你的for循环转换在Java中是这样的:

for (Iterator<Node> it = children.iterator(); it.hasNext();) { 
    Node node = it.next(); 
    // The rest of it 
} 

所以,即使你改变什么children是,你的迭代保持原样。

我建议使用Queue来帮助你在这里。

PS你真的想跳过所有的非第一个孩子吗?这似乎是你目前正在做的。

+0

@ Joe C:这也是我的想法。树也很大,它变得非常复杂。我想我需要使用不同的算法。我只是试图让第一个孩子和所有子孩子的逻辑在进入其他孩子之前开始工作。我可能不得不使用for循环或其他东西来覆盖所有的兄弟姐妹。但这已经是一场噩梦。大声笑 –