Java 后台生成 JSONArray 树

这篇博客介绍了两种在Java后台生成JSONArray树的方法。第一种是通过递归获取数据并拼接,但效率低下,消耗大量数据库访问和内存。第二种是优化后的方案,先获取所有数据,然后利用Map存储关系,通过遍历和递归快速生成树结构,大大提高了性能。
摘要由CSDN通过智能技术生成

java后台通过访问数据库得到数据来生成树是很常用的的方法

这个有很多种方法可以实现 我这里就说对我比较印象深刻的两种方法

一种是自己写的  后台拼接一点点的数据就要9秒之多

另一种是我借鉴我老大写得  后台拼接只要3面左右  (两种方法是在同样的数据和同样的环境中比较的)

为什么说这两种方法会对我影响比较大呢

因为这两种方法代表了两种实现思想

首先是我这个比较low的  我的思想就是先获取到根节点 然后通过根节点的 id  来查询所有 parentId = 根id 的数据

这样通过递归来实现 非常的慢 而且代码量非常的多

我也不怕丢人 贴出来给大家看看  

  /**
     * 递归树  java层数据
     * @param mapper
     * @param parentId
     * @return
     */
    public static List<TreeWyRoom> infiniteTree( WyRoomMapper mapper,Integer parentId,Integer xqId){
        List<TreeWyRoom> treeRooms = new ArrayList<>();
        WyRoomExample  example = new WyRoomExample();
        WyRoomExample.Criteria  ccc=example.createCriteria();
        ccc.andParentIdEqualTo(parentId);
        ccc.andXqIdEqualTo(xqId);
        List<WyRoom> wyRooms = mapper.selectByExample(example);
        Comparator<WyRoom> comparator = new Comparator<WyRoom>(){
            @Override
            public int compare(WyRoom o1, WyRoom o2) {
                return o1.getCode().compareTo(o2.getCode());
            }
        };


        Collections.sort(wyRooms,comparator);


        for( WyRoom wyRoom : wyRooms ){
            TreeWyRoom treeWyRoom = new TreeWyRoom();
            treeWyRoom.setId(wyRoom.getId());
            treeWyRoom.setParentId(wyRoom.getParentId());
            treeWyRoom.setLevel(wyRoom.getLevel());
            treeWyRoom.setPcId(wyRoom.getPcId());
            treeWyRoom.setXqId(wyRoom.getXqId());
            treeWyRoom.setCode(wyRoom.getCode());
            treeWyRoom.setAlias(wyRoom.getAlias());
            treeWyRoom.setType(wyRoom.getType());
            treeWyRoom.setCreateDate(wyRoom.getCreateDate());
            treeWyRoom.setCreator(wyRoom.getCreator());
            treeWyRoom.setLastModDate(wyRoom.getLastModDate());
            treeWyRoom.setLastModifier(wyRoom.getLastModifier());
            treeRooms.add(treeWyRoom);
        }
        for(TreeWyRoom treeRoom : treeRooms){
            if(treeRoom.getLevel()==2){
                treeRoom.setPlzj(true);
            }
            treeRoom.setChildren(infiniteTree(mapper,treeRoom.getId(),xqId));
        }
        return treeRooms;
    }


    /**
     * 把递归树拼接成JSON
     * @param treeRoom
     * @param o
     * @return
     */
    public

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值