开箱即用系列-工具包-树形结构链表排序(递归)

使用背景:

  1. 菜单树结构的数据,需要排序的时候.

菜单级别-树结构排序

maven依赖:
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20<version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>
代码实现:

import com.bruce.tool.common.util.ClassUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SortUtils {

    public static <E> List<E> tree(List<E> entities,String idKey,String pidKey) {
        Integer rootId = 0;
        Map<Integer,List<E>> parents = Maps.newConcurrentMap();
        Map<Integer,E> nodes = Maps.newConcurrentMap();
        for (E entity : entities) {
            Integer id = ClassUtils.getValue(entity,idKey);
            Integer pid = ClassUtils.getValue(entity,pidKey);
            if( rootId > pid ){ rootId = pid;}
            nodes.put(id,entity);
            List<E> childrens = parents.get(pid);
            if(CollectionUtils.isEmpty(childrens) ){
                childrens = Lists.newArrayList();
                parents.put(pid,childrens);
            }
            childrens.add(entity);
        }

        if( CollectionUtils.isEmpty(nodes) ){ return entities; } // 结束排序

        List<E> rootNodes = Lists.newArrayList();
        for (Map.Entry<Integer,E> entry : nodes.entrySet()) {
            E entity = entry.getValue();
            Integer pid = ClassUtils.getValue(entity,pidKey);
            if( rootId.equals(pid) ){
                rootNodes.add(entity);
            }
        }

        List<E> sorted = Lists.newArrayList();
        recursion(parents,rootNodes,idKey,sorted);
        return sorted;
    }

    /**递归**/
    private static <E> void recursion(Map<Integer, List<E>> parents, List<E> childrens, String idKey, List<E> sorted){
        if( CollectionUtils.isEmpty(childrens) ){ return; }
        for (E children : childrens) {
            sorted.add(children);
            Integer id = ClassUtils.getValue(children,idKey);
            recursion(parents,parents.get(id),idKey, sorted);
        }
    }

}

补充说明:
若有改进建议,欢迎留言.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值