list和tree互转工具类

1、工具类

说明:
1.提供tree转list, list转tree两个方法,需要借助TreeNode接口然后实体类来实现。当然可以通过反射手段代替接口。
2.自己定义root标准,我这里是判断root的pid为’0"。(一般为"0"或null)
3.自定定义id类型,我这里是String类型。(一般为"Stirng"或"Long")
4.可以继续封装,定义TreeNodeImpl然后让实体类继承,这里不给出了。

/**
 * @author zevin
 * @date 2023/6/13 19:26
 */
public class TreeUtil {


    /**
     * 树节点接口
     *
     * @param <ID> id类型
     */
    public interface TreeNode<T extends TreeNode<T, ID>, ID> {
		ID getId();
		ID getParentId();
		boolean isRoot();
		Integer getSort();
		List<T> getChildren();
        T setChildren(List<T> children);
    }

    /**
     * list转tree
     *
     * @param all 所有节点
     */
    public static <T extends TreeNode<T, ID>, ID> List<T> list2Tree(List<T> all) {
        return list2Tree(null, all);
    }

    /**
     * list转tree
     *
     * @param parent 父节点
     * @param all    所有节点
     */
    public static <T extends TreeNode<T, ID>, ID> List<T> list2Tree(T parent, List<T> all) {
        return all.stream()
                .filter(node -> parent == null ? node.isRoot() : node.getParentId() != null && node.getParentId().equals(parent.getId()))
                .map(node -> node.setChildren(list2Tree(node, all)))
                .sorted(Comparator.comparingInt(TreeNode::getSort))
                .collect(Collectors.toList());
    }

    /**
     * tree转list
     *
     * @param all 所有节点
     */
    public static <T extends TreeNode<T, ID>, ID> List<T> tree2List(List<T> all) {
        return tree2List(all, new ArrayList<>());
    }

    /**
     * list转tree
     *
     * @param layer    同一层节点
     * @param nodeList 节点列表
     */
    public static <T extends TreeNode<T, ID>, ID> List<T> tree2List(List<T> layer, List<T> nodeList) {
        if (nodeList == null) nodeList = new ArrayList<>();
        if (layer == null || layer.isEmpty()) return nodeList;
        nodeList.addAll(layer);
        for (T item : layer) tree2List(item.getChildren(), nodeList);
        return nodeList;
    }
}

2、测试

    /**
     * 模拟实体类
     */
    @Data
    @Accessors(chain = true)
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Entity implements TreeNode<Entity, String>{
        private String id;
        private String pid;
        private Integer sort;
        private List<Entity> children;

        @Override
        public List<Entity> getChildren() {
            return children;
        }

        @Override
        public Entity setChildren(List<Entity> children) {
            this.children = children;
            return this;
        }

        @Override
        public Integer getSort() {
            return sort;
        }

        @Override
        public String getParentId() {
            return pid;
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public boolean isParentId() {
            return "0".equals(pid);
        }
    }
	
	/**
	 * 测试
	 */
    public static void main(String[] args) {
    	//1.准备数据
        Entity n1 = new Entity().setId("1").setPid("0").setSort(1);
        Entity n2 = new Entity().setId("2").setPid("0").setSort(2);
        Entity n3 = new Entity().setId("3").setPid("0").setSort(3);

        Entity n1_1 = new Entity().setId("1-1").setPid("1").setSort(1);
        Entity n1_2 = new Entity().setId("1-2").setPid("1").setSort(2);
        Entity n1_3 = new Entity().setId("1-3").setPid("1").setSort(3);

        Entity n2_1 = new Entity().setId("2-1").setPid("2").setSort(1);
        Entity n2_2 = new Entity().setId("2-2").setPid("2").setSort(2);
        Entity n2_3 = new Entity().setId("2-3").setPid("2").setSort(3);

        Entity n1_1_1 = new Entity().setId("1-1-1").setPid("1-1").setSort(1);
        Entity n1_1_2 = new Entity().setId("1-1-2").setPid("1-1").setSort(2);
        Entity n1_1_3 = new Entity().setId("1-1-3").setPid("1-1").setSort(3);
		
		//2.拼接tree
        n1.setChildren(Arrays.asList(n1_1, n1_2, n1_3));
        n2.setChildren(Arrays.asList(n2_1, n2_2, n2_3));
        n1_1.setChildren(Arrays.asList(n1_1_1, n1_1_2, n1_1_3));
        List<Entity> originalTree = new ArrayList<>(Arrays.asList(n1, n2, n3));
        
        //3.list和tree互转
        List<Entity> list = tree2List(originalTree);
        List<Entity> tree = list2Tree(list);
//        List<Entity> list = tree2List(originalTree, new ArrayList<>());
//        List<Entity> tree = list2Tree(null, list);
		
		//4.断点,查看结果
        System.out.println(list);
        System.out.println(tree);
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析的XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =
以下是一个简单的 Java 工具类,可以将 List 换为树形结构: ```java import java.util.*; public class TreeUtil { public static <T extends TreeNode> List<T> buildTree(List<T> nodes) { if (nodes == null || nodes.size() == 0) { return Collections.emptyList(); } Map<Long, T> nodeMap = new HashMap<>(); for (T node : nodes) { nodeMap.put(node.getId(), node); } List<T> rootNodes = new ArrayList<>(); for (T node : nodes) { T parent = nodeMap.get(node.getParentId()); if (parent != null) { parent.addChild(node); } else { rootNodes.add(node); } } return rootNodes; } public interface TreeNode { Long getId(); Long getParentId(); void addChild(TreeNode child); List<? extends TreeNode> getChildren(); } } ``` 这个工具类包含了一个通用的接口 `TreeNode`,通过实现这个接口,可以将任意类型的 List 换为树形结构。 `TreeNode` 接口包含了三个方法: - `getId()`:获取节点的唯一标识符。 - `getParentId()`:获取节点的父节点标识符。 - `addChild(TreeNode child)`:将一个子节点添加到当前节点。 - `getChildren()`:获取当前节点的所有子节点。 使用这个工具类非常简单,只需要将需要换的 List 传入 `buildTree()` 方法中即可: ```java List<MyNode> nodes = ...; // 获取需要换的 List List<MyNode> rootNodes = TreeUtil.buildTree(nodes); ``` 其中 `MyNode` 是一个实现了 `TreeNode` 接口的自定义类。注意,为了能够正确地构建树形结构,每个节点的 `getParentId()` 方法必须返回其父节点的 `getId()` 值。否则,节点将无法正确地添加到树中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值