我有一个List
的Nodes
其中包含 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/