【发布时间】:2016-09-19 20:51:41
【问题描述】:
我有一个List 的Nodes,其中包含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) 以在网页中呈现。