list转tree

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

/**
 * 将 list 结构数据转成 tree 结构
 *
 * @param nodeList            list 结构的数据
 * @param isRootNodeCondition pid 为根节点的条件。eg. (t) -> t == 0
 * @return List<Node>
 */
// public static List<Node> convertListToTreeNew(List<Node> nodeList, Predicate<Node> isRootNodeCondition) {
public static <T> List<T> convertListToTreeNew(List<T> nodeList,
                                               Function<T, ?> idFun,
                                               Function<T, ?> pidFun,
                                               Function<T, List<T>> getChildFun,
                                               BiConsumer<T, List<T>> setChildCon,
                                               Predicate<T> isRootNodeCondition) {
    // List<Node> treeList = new ArrayList<>();
    List<T> treeList = new ArrayList<>();
    // Map<Integer, Node> map = new ConcurrentHashMap<>();
    Map<Object, T> map = new ConcurrentHashMap<>();

    // 1 获取所有父节点
    // for (Node node : nodeList) {
    for (T node : nodeList) {
        // if (node.getPId() == 0) {
        if (isRootNodeCondition.test(node)) {
            treeList.add(node);
        }
        // map.put(node.getId(), node);
        map.put(idFun.apply(node), node);
    }
    log.info("获取所有父节点 treeList:[{}]", JsonUtil.toJson(treeList));

    // 2 获取某个节点的父节点,然后将其添加到其父节点的子节点列表中
    // for (Node node : nodeList) {
    for (T node : nodeList) {
        // final Node pNode = map.get(node.getPId());
        final T pNode = map.get(pidFun.apply(node));
        if (pNode != null) {
            // final List<Node> childList = pNode.getChild();
            final List<T> childList = getChildFun.apply(pNode);
            if (childList == null) {
                // pNode.setChild(new ArrayList<>());
                setChildCon.accept(pNode, new ArrayList<>());
            }
            // pNode.getChild().add(node);
            getChildFun.apply(pNode).add(node);
        }
        // final List<Node> child = node.getChild();
        final List<T> child = getChildFun.apply(node);
        if (child == null) {
            // node.setChild(new ArrayList<>());
            setChildCon.accept(node, new ArrayList<>());
        }
    }
    log.info("组装完成的 tree 结构:[{}]", JsonUtil.toJson(treeList));
    return treeList;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值