{ "id":165, "parentId":0, "childList":[ { "id":1888, "parentId":165, "childList":[ { "id":1999, "parentId":1888, "childList":[ ] } ] }, { "id":1889, "parentId":165, "childList":[ ] } ] }级联新增java的lamda代码
时间: 2023-07-06 21:35:31 浏览: 133
li:hover的解决方案
下面是实现级联新增的 Java Lambda 代码:
```
public class TreeNode {
private int id;
private int parentId;
private List<TreeNode> childList;
public TreeNode(int id, int parentId) {
this.id = id;
this.parentId = parentId;
this.childList = new ArrayList<>();
}
public void addChild(TreeNode child) {
childList.add(child);
}
public int getId() {
return id;
}
public int getParentId() {
return parentId;
}
public List<TreeNode> getChildList() {
return childList;
}
}
public class Tree {
private List<TreeNode> nodeList;
public Tree() {
this.nodeList = new ArrayList<>();
}
public void addNode(TreeNode node) {
nodeList.add(node);
}
public List<TreeNode> getNodeList() {
return nodeList;
}
public List<TreeNode> findChildren(int parentId) {
return nodeList.stream()
.filter(node -> node.getParentId() == parentId)
.collect(Collectors.toList());
}
public void createTree(int rootId) {
TreeNode rootNode = new TreeNode(rootId, 0);
addNode(rootNode);
createChildren(rootNode);
}
private void createChildren(TreeNode parentNode) {
List<TreeNode> children = findChildren(parentNode.getId());
children.forEach(child -> {
parentNode.addChild(child);
createChildren(child);
});
}
}
public class Main {
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree(165);
TreeNode newNode = new TreeNode(2000, 1999);
TreeNode parentNode = tree.getNodeList().stream()
.filter(node -> node.getId() == 1999)
.findFirst()
.orElse(null);
if (parentNode != null) {
parentNode.addChild(newNode);
}
System.out.println(tree.getNodeList());
}
}
```
其中,`TreeNode` 表示树节点,`Tree` 表示树结构,`Main` 类中的 `main` 方法演示了如何创建树、查找节点和添加子节点。使用 Java Lambda 表达式可以简洁地实现对树的遍历和查找操作。
阅读全文