JAVA8 两行代码实现ID-PID转树状结构

JAVA8 两行代码实现ID-PID转树状结构

核心逻辑
  • 通过stream对集合进行分组

    准备知识:java8的收集器groupingBy 可以根据项目的一个属性的值对流中的项目分组,并将属性值作为结果Map的键,利用这个特性,可以按列表对象中的Pid属性进行分组。

    Stream收集器groupingBy示意图:
    在这里插入图片描述

  • 第二步,遍历原集合,从Map中取出对应的List存进去。

测试用Entity
@Data
public class TestEntity {
    /** 必备的结构属性 **/
    //id
    private int id;
    //父id
    private int pid;
    //子集合
    private List<TestEntity> children;

    /** 私有属性,与业务相关的属性 **/
    //名称
    private String name;
}
代码(想直接用看这里)
  • 单一顶层节点的实现方式
/**
     * 将id-pid转为tree结构,单一顶层节点,顶层节点的id和pid不能相同
     * @param pidList id-pid对象的列表
     * @return tree结构对象
     */
    public TestEntity buildTree(List<TestEntity> pidList){
       //以pid为Key进行分组存入Map
        Map<Integer,List<TestEntity>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(TestEntity::getPid));
        pidList.stream().forEach(item->item.setChildren(pidListMap.get(item.getId())));
        //取出顶层节点的对象,本例顶层节点的"PID"为0,注意是PID
        return pidListMap.get(0).get(0);
    }
  • 多个顶层节点的实现方式: 原来的实现稍加修改,只在需要修改的地方加了注释,便于查看区别
    //返回值改为List
    public List<TestEntity> buildTree(List<TestEntity> pidList){
        Map<Integer,List<TestEntity>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(TestEntity::getPid));
        pidList.stream().forEach(item->item.setChildren(pidListMap.get(item.getId())));
        //返回结果也改为返回顶层节点的list
        return pidListMap.get(0);
    }
小结

Id-pid转树是一个很常见的需求,以前的实现方式都是基于递归,总是要写老长,还得单独提供一个递归方法,转一个数据结构,要写那么长,总感觉“长不配位”。现在java8逐渐在项目中普及起来了,使用stream可以很方便很清晰的来实现Id-pid转树的需求。

附录:测试代码
public class TestMain {
    public static void main(String[] args) {
        /** 构造数据 **/
        final List<TestEntity> testEntities = new ArrayList<TestEntity>();
        TestEntity topEntity = new TestEntity();
        topEntity.setPid(0);
        topEntity.setId(1);
        topEntity.setName("我是顶层");
        testEntities.add(topEntity);
        IntStream.range(2,10).forEach(i->{
            TestEntity testEntity = new TestEntity();
            testEntity.setId(i);
            testEntity.setPid(1);
            testEntity.setName("name_" + i);
            testEntities.add(testEntity);
            IntStream.range(i * 10,(i * 10 + 5)).forEach(subI->{
                TestEntity subEntity = new TestEntity();
                subEntity.setId(subI);
                subEntity.setPid(i);
                subEntity.setName("name_" + subI);
                testEntities.add(subEntity);
                IntStream.range(subI * 10,(subI * 10 + 3)).forEach(subII->{
                    TestEntity sub2Entity = new TestEntity();
                    sub2Entity.setId(subII);
                    sub2Entity.setPid(subI);
                    sub2Entity.setName("name_" + subII);
                    testEntities.add(sub2Entity);
                });
            });
        });
        testEntities.stream().forEach(item->{
            System.out.println(JSON.toJSONString(item));
        });
        System.out.println("========================================");
        /** 测试 **/
        Pid2TreeTest pid2TreeTest = new Pid2TreeTest();
        TestEntity testEntitiy = pid2TreeTest.buildTree(testEntities);
        System.out.println(JSON.toJSONString(testEntitiy));
    }
}
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值