collection
Collections.emptyList()方法返回一个空的list,使用前提是不会再对返回的list进行增加和删除操作;
Collectors.toList()方法是将流中的所有元素导出到一个列表中,过滤是filter,运算是map,去重是distinct。
例子
组织结构实体类
package com.spiov.wx.basedata.vo;
import java.util.ArrayList;
import java.util.List;
/**
* 组织结构节点
*
* @author guozh
* @date 2022/2/16 15:40
*/
public class OrganizationNode {
/**
* 结构id
*/
private Integer id;
/**
* 结构名称
*/
private String name;
/**
* 层级
*/
private Integer level;
/**
* 子节点
*/
private List<OrganizationNode> children = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public List<OrganizationNode> getChildren() {
return children;
}
public void setChildren(List<OrganizationNode> children) {
this.children = children;
}
}
Controller
/**
* 组织机构树
* @param request
* @return com.spiov.wx.util.CommonResponse
* @author guozh
* @date 2022/2/16 17:13
*/
@GetMapping("/tree")
public CommonResponse tree(HttpServletRequest request){
CommonResponse instance = CommonResponse.getInstance();
Integer companyId = Integer.valueOf(HttpUtil.getCompanyId(request));
List<OrganizationNode> list = iDepartmentInfoService.tree(companyId);
instance.setResultData(list);
return instance;
}
ServiceImpl
@Override
public List<OrganizationNode> tree(Integer companyId) {
List<DepartmentInfo> list = super.list(Wrappers.<DepartmentInfo>lambdaQuery()
.eq(DepartmentInfo::getWxCompanyId,companyId)
.eq(DepartmentInfo::getDeleted,"0")
.eq(DepartmentInfo::getStatus,"0"));
if (CollectionUtils.isNotEmpty(list)){
List<OrganizationNode> nodeList = new ArrayList<>();
//过滤顶级数据
List<DepartmentInfo> rootList = list.stream().filter(e -> Objects.isNull(e.getParentId())).collect(Collectors.toList());
if (rootList.isEmpty()){
return nodeList;
}
rootList.forEach(e ->{
OrganizationNode node = new OrganizationNode();
node.setId(e.getId());
node.setName(e.getName());
node.setLevel(1);
getChildren(node.getId(),list,node.getChildren(),node.getLevel());
nodeList.add(node);
});
return nodeList;
}
return Collections.emptyList();
}
public void getChildren(Integer parentId, List<DepartmentInfo> dataList, List<OrganizationNode> children, Integer level){
List<DepartmentInfo> list = dataList.stream().filter(e -> Objects.equals(parentId, e.getParentId())).collect(Collectors.toList());
if (list.isEmpty()){
return;
}
list.forEach(e -> {
OrganizationNode node = new OrganizationNode();
node.setId(e.getId());
node.setName(e.getName());
node.setLevel(level + 1);
getChildren(node.getId(),dataList,node.getChildren(),node.getLevel());
children.add(node);
});
}