java:list<Map<String,Object>>树形结构怎么生成,不用for循环嵌套
时间: 2023-10-14 21:00:46 浏览: 108
你可以使用递归来生成树形结构,而不使用嵌套的循环。下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TreeGenerator {
public static List<Map<String, Object>> generateTree(List<Map<String, Object>> flatList, String parentIdKey, String idKey) {
List<Map<String, Object>> treeList = new ArrayList<>();
Map<Object, List<Map<String, Object>>> childMap = new HashMap<>();
// 将所有节点按照父节点分组
for (Map<String, Object> node : flatList) {
Object parentId = node.get(parentIdKey);
childMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
}
// 递归生成树形结构
generateChildren(childMap, treeList, null, idKey);
return treeList;
}
private static void generateChildren(Map<Object, List<Map<String, Object>>> childMap,
List<Map<String, Object>> parentList,
Object parentId,
String idKey) {
List<Map<String, Object>> children = childMap.get(parentId);
if (children != null) {
for (Map<String, Object> child : children) {
Object childId = child.get(idKey);
List<Map<String, Object>> grandChildren = new ArrayList<>();
child.put("children", grandChildren);
generateChildren(childMap, grandChildren, childId, idKey);
}
parentList.addAll(children);
}
}
public static void main(String[] args) {
// 示例用法
List<Map<String, Object>> flatList = new ArrayList<>();
Map<String, Object> node1 = new HashMap<>();
node1.put("id", 1);
node1.put("parentId", null);
flatList.add(node1);
Map<String, Object> node2 = new HashMap<>();
node2.put("id", 2);
node2.put("parentId", 1);
flatList.add(node2);
Map<String, Object> node3 = new HashMap<>();
node3.put("id", 3);
node3.put("parentId", 1);
flatList.add(node3);
Map<String, Object> node4 = new HashMap<>();
node4.put("id", 4);
node4.put("parentId", 2);
flatList.add(node4);
List<Map<String, Object>> treeList = generateTree(flatList, "parentId", "id");
System.out.println(treeList);
}
}
```
这个示例代码中,`generateTree` 方法接受一个扁平的节点列表 `flatList`,以及两个键的名称:`parentIdKey` 和 `idKey`。它首先将节点按照父节点进行分组,然后通过递归调用 `generateChildren` 方法来构建树形结构。最后返回生成的树形结构列表。
你可以根据自己的数据结构和需求进行相应的修改。希望这能帮到你!
阅读全文