小工具-集合构造树形结构

/**
 * 集合树形转换
 *
 * @param list          需要转换的集合
 * @param tClass        集合中对象类型
 * @param parentIdField 父节点字段
 * @param nodeField     下级节点字段
 * @param parentId      父节点
 * @param <T>           集合中对象类型
 * @return
 * @throws NoSuchFieldException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
public static <T> List<T> getTree(List<T> list, Class<? extends T> tClass, String idField, String parentIdField, String nodeField, long parentId)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    List<T> result = new ArrayList<>();
    //当前节点方法
    idField = idField.replaceFirst(idField.substring(0, 1), idField.substring(0, 1).toUpperCase());
    Method methodId = tClass.getMethod("get" + idField);
    //父节点方法
    parentIdField = parentIdField.replaceFirst(parentIdField.substring(0, 1), parentIdField.substring(0, 1).toUpperCase());
    Method methodParent = tClass.getMethod("get" + parentIdField);
    //下级节点方法
    nodeField = nodeField.replaceFirst(nodeField.substring(0, 1), nodeField.substring(0, 1).toUpperCase());
    Method methodNode = tClass.getMethod("set" + nodeField, List.class);
    for (T t : list) {
        long id = (long) methodId.invoke(t);
        if (methodParent.invoke(t).equals(parentId)) {//找到下级节点
            methodNode.invoke(t, getTree(list, tClass, idField, parentIdField, nodeField, id));
            result.add(t);
        }
    }
    return result;
}

方法直接可用,将list集合构造成为树形结构;当然也可以改造成为数组、Set、Map等集合形式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑谈子云亭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值