JDK8新特性之Stream流的应用(一)
需求是生成部门的树结构,这个需要递归循环部门列表查找部门子级,其耗时会因为其层级与成员的多寡而不断的增长,为了提高效率,使用了JDK8新特性---Stream流。
package com.tinghs.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Department {
private Integer id;
private String name;
private Integer parentId;
private List<Department> children = new ArrayList<>();
public Department(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
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 getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<Department> getChildren() {
return children;
}
public void setChildren(List<Department> children) {
this.children = children;
}
private static List<Department> makeTree(List<Department> departmentList, Integer pId) {
//子部门
List<Department> children = departmentList.stream().filter(x -> x.getParentId() == pId).collect(Collectors.toList());
//后辈中的非子级
List<Department> successor = departmentList.stream().filter(x -> x.getParentId() != pId).collect(Collectors.toList());
children.forEach(x ->
{
makeTree(successor, x.getId()).forEach(
y -> x.getChildren().add(y)
);
}
);
return children;
}
}

浙公网安备 33010602011771号