三级城市树的遍历

mac2025-08-14  12

public List<CityBean> getCityTree() { List<CityBean> firstCity = cityDao.getCityTree("", "0"); List<CityBean> firstTreeCity=new ArrayList<>(); for (CityBean cityBean:firstCity){ List<CityBean> secondCity = cityDao.getCityTree(cityBean.getId(), ""); if(secondCity!=null) { List<CityBean> secondTreeCity = new ArrayList<>(); for (CityBean cityBean2 : secondCity) { List<CityBean> secondChildren = cityDao.getCityTree(cityBean2.getId(), ""); cityBean2.setChildren(secondChildren); secondTreeCity.add(cityBean2); } cityBean.setChildren(secondTreeCity); } firstTreeCity.add(cityBean); } return firstTreeCity; }

递归写法(推荐):

public List<CityBean> getChild(String id){ List<CityBean> firstTreeCity=new ArrayList<>(); List<CityBean> treeMenu = cityDao.getCityTree(id, ""); if(treeMenu.size()>0){ for (CityBean cityBean : treeMenu) { cityBean.setChildren(getChild(cityBean.getId())); firstTreeCity.add(cityBean); } } return firstTreeCity; } @Override public List<CityBean> getCityTree() { List<CityBean> firstCity = cityDao.getCityTree("", "0"); List<CityBean> firstTreeCity=new ArrayList<>(); for (CityBean cityBean:firstCity){ cityBean.setChildren(getChild(cityBean.getId())); firstTreeCity.add(cityBean); } return firstTreeCity; } <select id="getCityTree" resultType="io.renren.modules.practice.bean.CityBean" parameterType="string"> select id,parent_id parentId,chs_name chsName,type type,create_time createTime from ff_city where is_delete=90 <if test="parentId!=null and parentId!=''"> and parent_id=#{parentId} </if> <if test="type!=null and type!=''"> and type=#{type} </if> </select> List<CityBean> getCityTree(@Param("parentId") String parentId,@Param("type") String type);
最新回复(0)