构建树形结构集合的方法-Java

完整代码如下

构建树形结构方法

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TableUtils<T> {

    /**
     * 集合构建成层级结构
     *
     * ps:处于顶级的数据,上下级字段值必须为空
     *
     * @param list 集合
     * @param primaryKeyName 主键字段名称
     * @param nodeName 上下级字段名称
     * @param childName 存放子集合的字段名称
     * @param splitter 分割符  ps: 没有则传null
     * @return 层级结构的集合
     */
    public static <T> List<T> tree(List<T> list, String primaryKeyName, String nodeName, String childName, String splitter) {
        List<T> topNode = new ArrayList<>();
        try {
            LinkedList<T> linkedList = new LinkedList<>(list);
            while (!linkedList.isEmpty()) {
                T first = linkedList.removeFirst();
                Object nodeObj = getDeclaredFieldValue(first, nodeName);
                Object primaryKeyObj = getDeclaredFieldValue(first, primaryKeyName);
                Field childFiled = getDeclaredField(first, childName);
                if (JudgeUtils.isNull(childFiled.get(first))) {
                    childFiled.set(first, new ArrayList<>());
                }
                List<T> childList = (List<T>) childFiled.get(first);
                if (JudgeUtils.isEmpty(splitter)) {
                    if (JudgeUtils.isNull(nodeObj)) {
                        topNode.add(first);
                    }
                    for (T node : linkedList) {
                        Object secondNodeObj = getDeclaredFieldValue(node, nodeName);
                        String secondNode = JudgeUtils.isNull(secondNodeObj) ? "" :  String.valueOf(secondNodeObj);
                        if ((secondNode.equals(String.valueOf(primaryKeyObj)))) {
                            childList.add(node);
                        }
                    }
                } else {
                    String nodeValue = "";
                    if (JudgeUtils.isNull(nodeObj)) {
                        nodeValue += primaryKeyObj;
                        topNode.add(first);
                    } else {
                        String nodeCon = (String) nodeObj;
                        String node = nodeCon.endsWith(splitter) ? nodeCon.substring(0, nodeCon.lastIndexOf(splitter)) : nodeCon;
                        nodeValue = node + splitter + primaryKeyObj;
                    }
                    for (T node : linkedList) {
                        Object secondNodeObj = getDeclaredFieldValue(node, nodeName);
                        String secondNodeCon = JudgeUtils.isNull(secondNodeObj) ? "" : (String) secondNodeObj;
                        String secondNode = secondNodeCon.endsWith(splitter) ? secondNodeCon.substring(0, secondNodeCon.lastIndexOf(splitter)) : secondNodeCon;
                        if (nodeValue.equals(secondNode)) {
                            childList.add(node);
                        }
                    }
                }
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return topNode;
    }

    private static <T> Field getDeclaredField(T clz, String fieldName) throws NoSuchFieldException {
        Field field = clz.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return field;
    }

    private static <T> Object getDeclaredFieldValue(T clz, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        return getDeclaredField(clz, fieldName).get(clz);
    }

}

用到的校验方法

import java.lang.reflect.Field;

/**
 * 检验工具类
 */
public class JudgeUtils<T> {

    /**
     * 判断字符串为空
     *
     * @param str 字符串
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim());
    }

    /**
     * 判断对象为空
     *
     * @param o 对象
     */
    public static boolean isNull(Object o) {
        return o == null;
    }

    /**
     * 判断对象及其字段全为空
     *
     * @param o 对象
     */
    public static boolean isAllNull(Object o) {
        boolean flag = isNull(o);
        if (!flag) {
            try {
                for (Field field : o.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    if (!isNull(field.get(o))) {
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 断言-true则报错
     *
     * @param state 状态
     * @param msg 报错内容
     */
    public static void assertion(boolean state, String msg) {
        if (state) {
            throw new RuntimeException(msg);
        }
    }

    /**
     * 断言-检查对象不为空-true则报错-false则返回该对象
     *
     * @param t 对象
     * @param msg 报错内容
     */
    public static<T> T checkNotNull(T t, String msg) {
        if (t instanceof String) {
            assertion(isEmpty((String) t), msg);
        } else {
            assertion(isNull(t), msg);
        }
        return t;
    }

    /**
     * 断言-检查对象为空-true则返回该对象-false则报错
     *
     * @param t 对象
     * @param msg 报错内容
     */
    public static<T> T checkIsNull(T t, String msg) {
        if (t instanceof String) {
            assertion(!isEmpty((String) t), msg);
        } else {
            assertion(!isNull(t), msg);
        }
        return t;
    }

}

测试用例

测试表对象

import java.util.ArrayList;
import java.util.List;

public class TableTest {

    /**
     * 主键字段
     */
    private Long id;

    /**
     * 上下级字段(示例:1,3,5)
     * ps:顶级该值要为空
     */
    private String node;

    /**
     * 子集合字段
     */
    private List<TableTest> list = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNode() {
        return node;
    }

    public void setNode(String node) {
        this.node = node;
    }

    public List<TableTest> getList() {
        return list;
    }

    public void setList(List<TableTest> list) {
        this.list = list;
    }

    public TableTest() {
    }

    public TableTest(Long id, String node, List<TableTest> list) {
        this.id = id;
        this.node = node;
        this.list = list;
    }

    @Override
    public String toString() {
        return "TableTest{" +
                "id=" + id +
                ", node='" + node + '\'' +
                ", list=" + list +
                '}';
    }
}

测试方法

import cn.cgj.system.domain.TableTest;
import cn.cgj.util.TableUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class UnitTest {

    @Test
    public void test() throws NoSuchFieldException, IllegalAccessException {
        TableTest tableTop1 = new TableTest(1L, null, null);
        TableTest tableTop2 = new TableTest(2L, null, null);
        TableTest tableSon1 = new TableTest(3L, "1", null);
        TableTest tableSon2 = new TableTest(4L, "2,", null);
        TableTest tableSon3 = new TableTest(5L, "1,3", null);
        TableTest tableSon4 = new TableTest(6L, "2,4,", null);

        List<TableTest> list = new ArrayList<TableTest>() {{
            add(tableTop1);
            add(tableTop2);
            add(tableSon1);
            add(tableSon2);
            add(tableSon3);
            add(tableSon4);
        }};

        List<TableTest> hierarchy = TableUtils.tree(list, "id", "node", "list", ",");
        hierarchy.forEach(System.err::print);
    }
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值