项目中需要传递组织机构数据,因为要校验上级站点是否存在(存在才能插入,除非根节点),然后就有了这个代码
/**
* 双重for循环方法转换成树形结构
* @param zCompanyBeanList
* @return
*/
public static List<ZCompanyBean> buildTreeCompany(List<ZCompanyBean> zCompanyBeanList) {
List<ZCompanyBean> result = new LinkedList<>();
for (ZCompanyBean zCompanyBean : zCompanyBeanList) {
if (StringUtils.isEmpty(zCompanyBean.getParent_id())) {
result.add(zCompanyBean);
}
for (ZCompanyBean child : zCompanyBeanList) {
if (child.getParent_id().equals(zCompanyBean.getCode())) {
List<ZCompanyBean> children = zCompanyBean.getChildren();
if (children == null) {
children = new LinkedList<>();
zCompanyBean.setChildren(children);
}
children.add(child);
}
}
}
return result;
}
其中实体类如下
@Data
public class ZCompanyBean {
/**
* 部门编码
*/
private String code;
/**
* 上级部门
*/
private String parent_id;
/**
* 部门name
*/
private String name;
private String remark;
/**
* 部门状态0:正常 1:删除 3:停职 4离职 5 退休
*/
private String is_enable;
private String oOrgCode;
/**
* 层级(用于批量传)
*/
private int level;
private List<ZCompanyBean> children;
}
转化成一个树后还需要使用广度遍历,这样可以把一个层级的批量传过去
定义个level属性(层级)
/**
* 广度遍历层级(公司)
* @param zCompanyBeanList
*/
public static void spanForLevelCompany(List<ZCompanyBean> zCompanyBeanList){
Queue<ZCompanyBean> queue = new LinkedList<>();
for (ZCompanyBean zCompanyBean:zCompanyBeanList) {
int level = 0;
zCompanyBean.setLevel(level);
queue.add(zCompanyBean);
ZCompanyBean tree ;
tree = queue.poll();
while (null != tree) {
if(null!=tree.getChildren()) {
for (ZCompanyBean tr : tree.getChildren()) {
tr.setLevel(tree.getLevel()+1);
queue.offer(tr);
}
}
tree = queue.poll();
}
}
}
最后是main方法
//构建树
List<ZCompanyBean> zCompanyTreeList = TreeUtils.buildTreeCompany(zCompanyBeanList);
//广度遍历层级(公司)
TreeUtils.spanForLevelCompany(zCompanyTreeList);
Map<Integer,List<Map<String, Object>>> map = new HashMap<>(10);
//将传的数据分层级
getLevelMap(zCompanyTreeList,map);
for(int i=0;i<map.size();i++){
List<Map<String, Object>> companyLevelList = map.get(i);
List<List<Map<String, Object>>> parts = Lists.partition(companyLevelList, maxPostSize);
for (List<Map<String, Object>> part:parts) {
***post传递参数***
}
}
附录getLevelMap方法
public void getLevelMap(List<ZCompanyBean> result,Map<Integer,List<Map<String, Object>>> map){
List<Map<String, Object>> list = null;
for (ZCompanyBean zCompanyBean:result) {
Map<String, Object> param = new HashMap<>(10);
param.put("name", zCompanyBean.getName() + "");
param.put("department_id", zCompanyBean.getDepartment_id() + "");
param.put("code", zCompanyBean.getCode() + "");
String parentId = zCompanyBean.getParent_id() + "";
param.put("parent_id", parentId);
param.put("level", zCompanyBean.getLevel());
param.put("is_enable", zCompanyBean.getIs_enable());
int level = zCompanyBean.getLevel();
if(map.containsKey(level)){
list = map.get(level);
}else{
list = new LinkedList<>();
}
list.add(param);
map.put(level,list);
if(null!=zCompanyBean.getChildren()){
getLevelMap(zCompanyBean.getChildren(),map);
}
}
}