java8 list to tree 工具类

该文章提供了一个Java工具类ListToTreeUtil,用于将列表数据转换为树形结构。它使用了函数式编程接口如Function和BiConsumer,支持两种转换方法,分别适用于节点带有子节点列表字段和不带的情况。示例展示了如何使用这个工具类将Item对象列表构建为树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ListToTreeUtil

import lombok.Data;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class ListToTreeUtil {
   


    public static <T> List<Tree<T>> convertListToTree(List<T> nodeList, TreeConverter<T> converter) {
   
        if (nodeList == null || nodeList.isEmpty()) {
   
            return new ArrayList<>();
        }

        Map<Object, Tree<T>> nodeMap = new HashMap<>();
        List<Tree<T>> rootNodes = new ArrayList<>();

        // 将节点放入Map中,方便后续查找和创建树
        for (T item : nodeList) {
   
            Object itemId = converter.getItemId(item);
            Tree<T> treeNode = new Tree<>(itemId, item);
            nodeMap.put(itemId, treeNode);
        }

        // 遍历节点列表,将每个节点添加到其父节点的子节点列表中,或者作为根节点
        for (T item : nodeList) {
   
            Object parentId = converter.getParentId(item);

            if (parentId == null || !nodeMap.containsKey(parentId)) {
   
                // 没有父节点,将其视为根节点
                Tree<T> rootNode = nodeMap.get(converter.getItemId(item));
                rootNodes.add(rootNode);
            } else {
   
                Tree<T> parent = nodeMap.get(parentId);
                Tree<T> childNode = nodeMap.get(converter.getItemId(item));
                parent.addChild(childNode);
            }
        }

        return rootNodes;
    }

    public interface TreeConverter<T> {
   
        /**
         * 获取节点的唯一标识ID
         *
         * @param item 节点对象
         * @return 节点ID
         */
        Object getItemId(T item);

        /**
         * 获取节点的父节点ID
         *
         * @param item 节点对象
         * @return 父节点ID
         */
        Object getParentId(T item);
    }

    @Data
    public static class Tree<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值