迭代器组装树结构

以menu为例

class Menu{
	private Long id;
	private String name;
	private Long parentId;
	private List<Menu> children;
}
public static List<Menu> buildTreeIteratively(List<Menu> menus, Long rootParentId) {
        Map<Long, List<Menu>> menuMap = new HashMap<>();
        //1.构建 parentId -> 子节点列表 的映射
        for (Menu menu : menus) {
            menuMap.computeIfAbsent(menu.getParentId(), k -> new ArrayList<>()).add(menu);
        }
        //2.构建根节点
        List<Menu> rootNodes = menuMap.getOrDefault(rootParentId, new ArrayList<>());
        //3.使用迭代方式构建树
        Deque<Menu> stack = new ArrayDeque<>(rootNodes);
        while (!stack.isEmpty()) {
            Menu current = stack.pop();
            List<Menu> children = menuMap.get(current.getId());
            if (children != null) {
                current.setChildren(children);
                stack.addAll(children);
                return rootNodes;
            }
        }
        return rootNodes;
    }

你可能感兴趣的:(java)