在迭代期间交换集合

时间:2016-09-19 20:51:42

标签: java tree nodes

我有一个List Nodes,其中包含child nodes的嵌套列表。我试图遍历所有这些节点来查找特定节点。目前我从child nodes级别的root开始,然后深入到sub child node一级,依此类推使用{ {1}}循环。 这是我的代码:

for-each

如果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个孩子?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

因此即使你改变了children,你的迭代器仍保持不变。

我建议您使用Queue来帮助您。

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

相关问题