java 树
Posted jinnian18sui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 树相关的知识,希望对你有一定的参考价值。
1.实体
@Id
@Column( name = "REGION_ID")
private String regionId;
@Column( name = "REGION_CODE")
private String regionCode;
@Column( name = "REGION_NAME")
private String regionName;
@Column( name = "PARENT_ID")
private String parentId;
@Column( name = "STATE")
private Double state;
@Column( name = "REMARK")
private String remark;
@Column( name = "CREATED_TIME")
private Double createTime;
@Transient
private List<Region> children = new ArrayList<>();
2.获取当前节点
<select id="findParentList"
parameterType="java.lang.String"
resultType="cn.cloudwalk.isc.data.system.common.model.Region">
SELECT
*
FROM
`cw_ge_region_info`
<where>
<if test="regionCode != null and regionCode != ‘‘">
REGION_CODE = #{regionCode}
</if>
AND STATE = 1;
</where>
</select>
3.方法(获取当前节点下所有节点)
//先获取到所有数据
treeList=regionMapper.selectAll();
if(treeList==null) {return null;}
String regionCode = PropertiesUtil.getRegioncode();
Region dto = new Region();
dto.setState(1d);
dto.setRegionCode(regionCode);
List<Region> parentList = regionMapper.select(dto);
List<Region> list = new ArrayList<>();
if(parentList != null){
for (int i = 0; i < parentList.size(); i++) {
list.add(recursiveTree(parentList.get(i).getRegionId()));
}
}
return list;
}
* 递归算法解析成树形结构
* @param cid
*/
public Region recursiveTree(String cid) {
Region node = getRegionById(cid);
List<Region> childTreeNodes = getChildTreeById(cid);
for(Region child : childTreeNodes){
Region n = recursiveTree(child.getRegionId());
List<Region> list = node.getChildren();
list.add(n);
}
return node;
}
* 根据CID查询节点对象
*/
public Region getRegionById(String cid){
Map<String, Region> map = new HashMap<>(CommonConstant.HASHMAP_INITIALCAPACITY);
map = getTreeMap();
return (Region) map.get(cid);
}
* 一次性取所有数据,为了减少对数据库查询操作
* @return
*/
public Map<String, Region> getTreeMap(){
Map<String, Region> map = new HashMap<>(CommonConstant.HASHMAP_INITIALCAPACITY);
map = new HashMap<String, Region>();
if(null != treeList){
for(Region d : treeList){
map.put(d.getRegionId(), d);
}
}
return map;
}
* 根据父节点CID获取所有了节点
*/
public List<Region> getChildTreeById(String cid){
List<Region> list = new ArrayList<>();
if(null != treeList){
for (Region d : treeList) {
if(null != cid){
if (cid.equals(d.getParentId())) {
list.add(d);
}
}
}
}
return list;
}
以上是关于java 树的主要内容,如果未能解决你的问题,请参考以下文章