id|parent_id 1 | 0 2 | 1 3 | 1 4 | 1 5 | 1 6 | 0 java8 List没有子级的给于提示
时间: 2023-08-21 14:40:03 浏览: 40
你可以使用以下代码来实现你的需求:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Node {
private int id;
private int parentId;
private String name;
public Node(int id, int parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
List<Node> nodes = new ArrayList<>();
nodes.add(new Node(1, 0, "Node 1"));
nodes.add(new Node(2, 1, "Node 2"));
nodes.add(new Node(3, 1, "Node 3"));
nodes.add(new Node(4, 1, "Node 4"));
nodes.add(new Node(5, 1, "Node 5"));
nodes.add(new Node(6, 0, "Node 6"));
Map<Integer, Boolean> hasChildMap = new HashMap<>();
for (Node node : nodes) {
hasChildMap.put(node.getId(), false);
}
for (Node node : nodes) {
if (hasChildMap.containsKey(node.getParentId())) {
hasChildMap.put(node.getParentId(), true);
}
}
for (Node node : nodes) {
if (!hasChildMap.get(node.getId())) {
System.out.println(node.getName() + " has no child.");
}
}
}
}
```
这个代码中,我们首先定义了一个 `Node` 类,用来表示树节点。然后我们创建了一个节点列表 `nodes`,并添加了一些节点数据。接着我们创建了一个 `hasChildMap`,它是一个 `Map<Integer, Boolean>` 类型的映射,用来表示每个节点是否有子节点。初始时,我们将所有节点的 `hasChild` 值都设置为 `false`。接着我们遍历节点列表,如果某个节点的父节点在 `hasChildMap` 中,则将其父节点的 `hasChild` 值设置为 `true`。最后,我们再次遍历节点列表,找出所有 `hasChild` 值为 `false` 的节点,打印出它们的名称即可。
注意,这里的实现假定节点 ID 是连续的,从 1 开始递增。如果节点 ID 不是连续的,或者不是从 1 开始递增的,需要进行相应的修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)