【问题标题】:Swap collections during iteration在迭代期间交换集合
【发布时间】:2016-09-19 20:51:41
【问题描述】:

我有一个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 子级?

【问题讨论】:

  • 这似乎是一个 XY 问题。我会建议递归,但目前还不清楚你实际上想要做什么。
  • @JornVernee:我试图从一个数组列表构建一个 java 层次结构树,然后转换为 json (gson) 以在网页中呈现。

标签: java tree nodes


【解决方案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);

【讨论】:

  • 这正是我想要的。工作完美。谢谢!
【解决方案2】:

您不能像这样在迭代中进行交换。请记住,您的 for 循环在 Java 中是这样翻译的:

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

因此,即使您更改 children 是什么,您的迭代器也会保持原样。

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

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

【讨论】:

  • @Joe C:我也是这么想的。树也很大,向下移动变得非常复杂。我想我需要使用您所说的不同算法。我只是想让第一个孩子及其所有子孩子逻辑在进入其他孩子之前开始工作。我可能不得不使用 for 循环或其他东西来覆盖所有兄弟姐妹。但这已经是一场噩梦了。大声笑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2022-01-02
  • 2016-02-26
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多