通讯录树状查询

这篇博客探讨了如何在Java中实现通讯录的树状查询,首先从根节点开始递归添加子节点。之后,作者进一步介绍了如何集成模糊查询功能,利用VagueName字段进行以模糊名称为根节点的树状查询,从而提供更灵活的搜索体验。

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

逻辑是一开始查出根节点,然后一层层循环添加子节点

package com.service.system;

import com.alibaba.fastjson.JSONObject;
import com.dao.mybatis.CompanyMybatisDao;
import com.entity.database.CompanyEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class CompanyService {

    @Resource
    private CompanyMybatisDao companyMybatisDao;

    public JSONObject selectAll(CompanyEntity companyEntity) {
        JSONObject json = new JSONObject();

        /*查询出所有的数据*/
        List<CompanyEntity> treeData = companyMybatisDao.selectCompanyTrees(companyEntity);
        var departmentDtos = new ArrayList<CompanyEntity>();

        var departmentDtos2 = new ArrayList<CompanyEntity>();
        for (var t : treeData) {
            t.setChildren(childrenDepartTree(companyMybatisDao, t.getId()));
            departmentDtos.add(t);
        }
        /*进行树形结构封装*//*id  指的最大的id   0	滨投	company	 指这条数据*/
        if (companyEntity.getVagueName() != null) {
            List<CompanyEntity> companyEntities = childrenDepartTree2(departmentDtos, companyEntity.getVagueName(),departmentDtos2);
            json.put("data", companyEntities);

        } else {
            json.put("data", departmentDtos);
        }
        json.put("msg", "查询部门成功");
        json.put("code", 0);
        return json;

    }


    public static List<CompanyEntity> childrenDepartTree(CompanyMybatisDao companyMybatisDao, Integer id) {
        var param = new CompanyEntity();
        param.setParentId(id);
        var entity = companyMybatisDao.selectCompanyTrees(param);
        for (var e : entity) {
            e.setChildren(childrenDepartTree(companyMybatisDao, e.getId()));
        }
        return entity;
    }

    public static List<CompanyEntity> childrenDepartTree2(List<CompanyEntity> departmentDtos, String vagueName,List<CompanyEntity> departmentDtos2) {
        int i = 0;

        for (CompanyEntity a : departmentDtos
        ) {
            int i1 = a.getName().indexOf(vagueName);
            if (i1 == -1 &&a.getChildren()!=null) {
                childrenDepartTree2(a.getChildren(),vagueName,departmentDtos2);
            }else {
                departmentDtos2.add(a);
            }
        }
        return departmentDtos2;
    }


}

后来又加了模糊查询
字段VagueName;
以模糊字段为根节点,的树状查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值