思路:
先从集合中找出来顶级的菜单,然后遍历顶级菜单,找出每个顶级菜单的所有子菜单,然后判断当前需要排列的集合是否为空,如果不为空的话,就在遍历子菜单的下级菜单,直至没有需要排列的菜单。
使用迭代器,符合条件之后将数据删除们可以减少遍历的次数
package com.eleven;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* @author zhaojinhui
* @date 2021/6/4 15:11
* @apiNote
*/
public class ElevenTest {
public static void main(String[] args) {
TestChild one = new TestChild("1","1",null);
TestChild two = new TestChild("2","2","1");
TestChild sex = new TestChild("3","3","2");
List<TestChild> list = new ArrayList<>(3);
Collections.addAll(list,one,two,sex);
List<TestChild> tree = getTree(list);
System.out.println(tree);
}
public static List<TestChild> getTree(List<TestChild> testChildList){
List<TestChild> result = new ArrayList<>();
for (TestChild testChild : testChildList) {
if(StrUtil.isBlank(testChild.getParentId())){
result.add(testChild);
}
}
testChildList.removeAll(result);
for (TestChild testChild : result) {
setChildren(testChild,testChildList);
}
return result;
}
public static void setChildren(TestChild parent,List<TestChild> list){
List<TestChild> childList = new ArrayList<>();
for(Iterator<TestChild> iterator = list.iterator();iterator.hasNext();){
TestChild next = iterator.next();
if(parent.getCode().equals(next.getParentId())){
childList.add(next);
iterator.remove();
}
}
parent.setChildren(childList);
/**
判断子集集合是否为空比遍历整个集合是否为空要慢
if(CollUtil.isNotEmpty(childLlist)) {
for (TestChild testChild : childList) {
setChildren(testChild, list);
}
}
*/
if(CollUtil.isNotEmpty(list)) {
for (TestChild testChild : childList) {
setChildren(testChild, list);
}
}
}
}
@Data
@AllArgsConstructor
class TestChild{
private String name;
private String code;
private String parentId;
List<TestChild> children;
public TestChild(String name,String code,String parentId){
= name;
this.code = code;
this.parentId = parentId;
}
}