List转换为树形结构工具类

工具类

/**
 * @author yuanmengfan
 * @date 2023/3/21 13:23
 * @description 将list转换给树形结构
 */
public class TreeUtil {

    /**
     * 使用递归的方式实现。
     * 1.根据传入的parentValue找到所有根节点
     * 2.判断是否有找到根节点,
     *      如果没有则说明树不存在
     *      否则循环所有的根节点去判断他们是否有子节点。也就是把当前节点当做根节点。继续去寻找他的子节点。(递归1,,2)
     * 3.然后把找到的所有子节点,赋值给父节点
     * 4.最后返回所有的根节点就行。因为根节点的children字段已经被赋值了(如果有子节点的情况下。)
     *
     * Function 函数式接口 提供T,返回一个R
     * BiConsumer  函数式接口  提供T,U 执行对应的方法后,没有返回值。
     *
     * @param list       需要转换为tree的数据结构   必须需要包含一个id字段、parent字段、childrenField字段(子节点)
     * @param idField    提供一个节点通过Function返回对应的id值
     * @param parentIdFiled   提供一个节点通过Function返回对应的parentId值
     * @param parentValue     父节点的id值
     * @param childrenField   通过BiConsumer传入 父节点,及子节点(多个)为父节点设置children。
     * @param <T>        节点的类型
     * @param <R>        id与parent字段的类型
     *
     */
    public static  <T, R> List<T> listToTree(List<T> list, Function<T, R> idField, Function<T, R> parentIdFiled, R parentValue, BiConsumer<T,List<T>> childrenField) {
        if (list == null || list.size() <= 0) {
            return null;
        }

        List<T> rootLeaf = list.stream().filter(model -> Objects.equals(parentIdFiled.apply(model),parentValue )).collect(Collectors.toList());

        if (rootLeaf.size() > 0) {
            rootLeaf.forEach(model -> childrenField.accept(model,listToTree(list, idField,parentIdFiled,idField.apply(model), childrenField)));
        }
        return rootLeaf;
    }

    /**
     * 两次循环
     *      第一次循环:
     *          1.把所有根节点找出来
     *          2.把所有节点遍历得到一个map map中包含 key为parentId value为parentId=key的所有节点
     *      第二次循环:
     *          1.遍历所有节点得到每个节点的id值,然后去map里面寻找有没有当前这个id的key。
     *            如果有的话就代表key对应的value是当前这个节点的子节点。把所有子节点赋值给当前节点的子节点字段。
     * 最后返回所有根节点即可  
     */
    public static  <T, R> List<T> listToTree2(List<T> list, Function<T, R> idField, Function<T, R> parentIdFiled, R parentValue, BiConsumer<T,List<T>> childrenField) {
        HashMap<R, List<T>> map = new HashMap<>();

        List<T> result = new ArrayList<>();
        for (T t : list) {
            R parent = parentIdFiled.apply(t);
            if(Objects.equals(parent,parentValue)){
                result.add(t);
            }
            List<T> children = map.getOrDefault(parent, new ArrayList<T>());
            children.add(t);
            map.put(parent,children);
        }
        for (T t : list) {
            R id = idField.apply(t);
            List<T> children = map.get(id);
            childrenField.accept(t,children);
        }

        return result;
    }

    /**
     * Java8 使用 stream (两次循环)
     *      groupingBy -》是根据对象中的某字段的值去分组,相同的值为一个集合
     *      遍历所有节点得到每个节点的id值,然后去map里面寻找有没有当前这个id的key。
     * 最后返回所有根节点即可 
     */
    public static  <T, R> List<T> listToTree3(List<T> list, Function<T, R> idField, Function<T, R> parentIdFiled, R parentValue, BiConsumer<T,List<T>> childrenField) {
        Map<R, List<T>> collect = list.stream().collect(Collectors.groupingBy(parentIdFiled));
        list.forEach(model -> childrenField.accept(model,collect.get(idField.apply(model))));
        return list.stream().filter(model -> Objects.equals(parentIdFiled.apply(model),parentValue)).collect(Collectors.toList());
    }
}

测试

package com.util;

import com.alibaba.fastjson.JSONArray;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

class TreeUtilTest {


    @Test
    public void test(){
        Tree tree = new Tree();
        tree.setTitle("1");
        tree.setKey("1");
        tree.setParent("0");

        Tree tree1 = new Tree();
        tree1.setTitle("1.1");
        tree1.setKey("1.1");
        tree1.setParent("1");


        Tree tree2 = new Tree();
        tree2.setTitle("1.2");
        tree2.setKey("1.2");
        tree2.setParent("1");

        Tree tree3 = new Tree();
        tree3.setTitle("1.1.1");
        tree3.setKey("1.1.1");
        tree3.setParent("1.1");

        String rootParentValue = "0";

        List<Tree> list = Arrays.asList(tree, tree1, tree2, tree3);

        List<Tree> object = TreeUtil.listToTree(list, Tree::getKey, Tree::getParent, rootParentValue, Tree::setTrees);
        System.out.println("listToTree方法-》"+JSONArray.toJSONString(object));

        object = TreeUtil.listToTree2(list, Tree::getKey, Tree::getParent, rootParentValue, Tree::setTrees);
        System.out.println("listToTree2方法-》"+JSONArray.toJSONString(object));

        object = TreeUtil.listToTree3(list, Tree::getKey, Tree::getParent, rootParentValue, Tree::setTrees);
        System.out.println("listToTree3方法-》"+JSONArray.toJSONString(object));



    }


    @Data
    class Tree{
        String title;
        // id
        String key;
        String parent;
        // 子节点
        List<Tree> trees;
    }
}

返回结果

listToTree方法-[{"key":"1","parent":"0","title":"1","trees":[{"key":"1.1","parent":"1","title":"1.1","trees":[{"key":"1.1.1","parent":"1.1","title":"1.1.1","trees":[]}]},{"key":"1.2","parent":"1","title":"1.2","trees":[]}]}]
listToTree2方法-[{"key":"1","parent":"0","title":"1","trees":[{"key":"1.1","parent":"1","title":"1.1","trees":[{"key":"1.1.1","parent":"1.1","title":"1.1.1"}]},{"key":"1.2","parent":"1","title":"1.2"}]}]
listToTree3方法-[{"key":"1","parent":"0","title":"1","trees":[{"key":"1.1","parent":"1","title":"1.1","trees":[{"key":"1.1.1","parent":"1.1","title":"1.1.1"}]},{"key":"1.2","parent":"1","title":"1.2"}]}]

参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 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
发出的红包

打赏作者

假女吖☌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值