本文主要介绍了java递归设置层级菜单的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
思路:
先从集合中找出来顶级的菜单,然后遍历顶级菜单,找出每个顶级菜单的所有子菜单,然后判断当前需要排列的集合是否为空,如果不为空的话,就在遍历子菜单的下级菜单,直至没有需要排列的菜单。
使用迭代器,符合条件之后将数据删除们可以减少遍历的次数
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){
this.name = name;
this.code = code;
this.parentId = parentId;
}
}
到此这篇关于java递归设置层级菜单的实现的文章就介绍到这了,更多相关java 递归设置层级菜单内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:java递归设置层级菜单的实现
猜你喜欢
- JSP 制作验证码的实例详解 2023-07-30
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Java中的日期时间处理及格式化处理 2023-04-18
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19
- 深入了解Spring的事务传播机制 2023-06-02
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- JSP页面间传值问题实例简析 2023-08-03