思路:
先从集合中找出来顶级的菜单,然后遍历顶级菜单,找出每个顶级菜单的所有子菜单,然后判断当前需要排列的集合是否为空,如果不为空的话,就在遍历子菜单的下级菜单,直至没有需要排列的菜单。
使用迭代器,符合条件之后将数据删除们可以减少遍历的次数
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;
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(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){
this.name = name;
this.code = code;
this.parentId = parentId;
}
}
到此这篇关于java递归设置层级菜单的实现的文章就介绍到这了,更多相关java 递归设置层级菜单内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!