[英]Get all leaves elements of a recursive nested structure Data in java
有人可以帮助我如何进入 java 递归嵌套结构数据的所有叶子元素。
public class Item {
private String id;
private List<Item> items;
}
例子:
A
- AA
- aa1
- AB
- ab1
- abab1
- a1
结果
结果我只需要得到以下元素列表[aa1, abab1, a1]
在此先感谢您的帮助。
您可以以递归方式很容易地做到这一点:
public static List<Item> findLeaves(Item rootItem){
List<Item> leaves = new ArrayList<>();
recursivelyCollectLeaves(leaves, rootItem);
return leaves;
}
private static void recursivelyCollectLeaves(List<Item> leaves, Item actualItem){
if(actualItem.getItems().isEmpty()){
//No children, the actual item is a leaf
leaves.add(actualItem);
}
else{
for(Item child : actualItem.getItems()){
recursivelyCollectLeaves(leaves, child);
}
}
}
PS:为了使这段代码正常工作,请注意我在项目 class 中添加了吸气剂。
尝试将此方法添加到 class:
public List<Item> getLeaves() {
ArrayList<Item> list = new ArrayList<>();
if (items.size() == 0) {
list.add(this);
} else {
for (Item item : items) {
list.addAll(item.getLeaves());
}
}
return list;
}
它只是检查自己是否是一片叶子。 如果是,则返回自身,否则返回其子节点的所有叶子。
这个怎么样:
public class TestTest {
public static class Item {
private final String id;
private final List<Item> items;
public Stream<Item> getLeaves() {
if (items == null || items.isEmpty()) {
return Stream.of(this);
}
return items.stream()
.flatMap(Item::getLeaves);
}
}
public static void main(String[] args) {
final var item = new Item(
"A",
List.of(
new Item("AA",
List.of(new Item("aa1"))
),
new Item("AB",
List.of(new Item("ab1",
List.of(new Item("abab1")))
)
),
new Item("a1")
)
);
final var leaves = item.getLeaves()
.map(Item::getId)
.collect(Collectors.toList());
System.out.println(leaves);
}
}
注意:为简洁起见省略了构造函数和 getter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.