Execution effect chart
1. Create an entity class. This class is to store the id and parent id of the entity class that needs to traverse the parent-child relationship into this class, and finally use the tool class for unified traversal, so that the tool class can be universal ( most common tool classes will lose execution For the purpose of efficiency ), you can also refer to my traversal conditions to write a dedicated and more efficient method.
import lombok.Data;
//此注解为自动添加get、set、toString方法的,需要jar包,可自己生成getset,
@Data
public class Parent {
private Integer id;
private String name;
private Integer parentId;
public Parent(Integer id, String name, Integer parentId) {
super();
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
2. Add tool operation class
import java.util.ArrayList;
import java.util.List;
import com.xx.fresh.bean.Parent;
public class MakeList {
private List<Parent> list;
private List<Parent> resultList=new ArrayList<Parent>();
private String addName;
public void setAddName(String add) {
addName=add;
}
public void setList(List<Parent> list) {
this.list=list;
}
public List<Parent> getList(){
make();
return resultList;
}
private void make() {
for(Parent p:list) {
if(p.getParentId()==null) {
resultList.add(p);
//子菜单上加的横杠
String h="";
traverseList(p.getId(),h);
}
}
}
private void traverseList(int id,String h) {
h=h+addName;
for(Parent p:list) {
if(p.getParentId()!=null&&p.getParentId()==id) {
p.setName(h+p.getName());
resultList.add(p);
traverseList(p.getId(),h);
}
}
}
}
3. Invoke the method
//Classify(分类)是要遍历父子关系的实体类,
private List<Parent> doParent(List<Classify> list){
List<Parent> list2=new ArrayList<Parent>();
for(Classify c:list) {
list2.add(new Parent(c.getClassifyId(), c.getClassifyName(), c.getClassifyParentId()));
}
MakeList makeList=new MakeList();
makeList.setList(list2);
//在父子级前加上标识,可自定义或不写
makeList.setAddName("- ");
//通过调用工具类返回一个id、name、父id的排序后的列表
return makeList.getList();
}