java - 在迭代期间交换集合

标签 java tree nodes

我有一个ListNodes其中包含 child nodes 的嵌套列表。我正在尝试遍历所有节点以找到特定节点。目前我从 child nodes 开始来自root级别,然后深入一层至 sub child node等等使用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 交换并继续迭代等等。 有没有更好的方法来迭代嵌套 nodelist children ?

最佳答案

您可以将元素添加到队列中,并继续迭代直到队列为空(即您没有找到匹配项),而不是交换集合。或者您确实找到了匹配项并提前返回。

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);

关于java - 在迭代期间交换集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581901/

相关文章:

java - 系统找不到指定的路径

java - Tomcat 7 + JNI : UnsatisfiedLinkError: cannot open shared object file: No such file or directory

java - 关闭Scanner会影响性能吗

c - 如何在不使用递归和层序遍历的情况下求二叉树的高度?

.net - 需要帮助理解 TreeNodeCollection 的 .Net Collection 行为

java - Sublime Text 2 无法构建

java - 如何创建 B+ 树数据结构

json - 使用golang将treenode保存为json文件?

c++ - 链表中的无限循环

c++ - C++中的链表多个节点