java树形菜单 无限_分享一段自己写的无限级树形菜单代码 JAVA

由于工作中经常碰见树形结构所写的一个公用方法,虽然之前有过无限级的代码不过都限制于对象,对象不同或对象中字段不同都无法使用。

此方法可以接受任意类型的List集合,返回时是已经拼接好了所有子集的List集合。注意方法接收的List合返回的List是同一个对象。

此方法采用的是Map形式实现,所以在参数方面需要提供字段名,这样就可以避免父级和自己字段不同从而多写很多重复的代码。另外子集的名称是可以自定义的。如果名字和我重构方法中相同可以用重构方法(其实这个没啥用就是可能方便一点)

自己写的大佬勿喷,如果有更好的方式可以评论,感谢大家!

private static List> all;

/**

*

* @param list 任何类型的list集合

* @param id 本层的id的字段名

* @param parentId 上一层Id的字段名

* @param childrenListName 对象中子集的名

* @param firstId 最高层的父级Id

* @return 返回任意类型List

* @throws Exception 转换异常

*/

public static List toJson(List> list, String id, String parentId, String childrenListName,Integer firstId) throws Exception {

List> mapList = new ArrayList<>();

for(Object o : list){

Map map = ObjectToMapUtils.objectToMap(o);

mapList.add(map);

}

all = new ArrayList<>(mapList);

List> root = new ArrayList<>();

for(Map map : mapList){

if(Integer.parseInt(map.get(parentId).toString()) == firstId){

root.add(map);

}

}

all.removeAll(root);

for(Map map : root){

map.put(childrenListName,getChildren(map,id,parentId,childrenListName));

}

Gson gson = new Gson();

List lists = gson.fromJson(JSONObject.toJSONString(root),list.getClass());

return lists;

}

public static List toJson(List> list) throws Exception{

return toJson(list,"id","parentId","list",-1);

}

public static List toJson(List> list,String id) throws Exception{

return toJson(list,id,"parentId","list",-1);

}

public static List toJson(List> list,String id,String parentId) throws Exception{

return toJson(list,id,parentId,"list",-1);

}

public static List toJson(List> list,String id,String parentId,String childrenListName) throws Exception{

return toJson(list,id,parentId,childrenListName,-1);

}

public static List> getChildren(Map parent,String id,String parentId,String childrenListName){

List> mapList;

if(parent.containsKey(childrenListName) && parent.get(childrenListName) != null){

mapList = (List>) parent.get(childrenListName);

}else{

mapList = new ArrayList<>();

}

for(Map map : all){

if(Integer.parseInt(parent.get(id).toString()) == Integer.parseInt(map.get(parentId).toString())){

mapList.add(map);

}

}

if(mapList != null){

all.removeAll(mapList);

for(Map map : mapList){

map.put(childrenListName,getChildren(map,id,parentId,childrenListName));

}

}

return mapList;

}

public static void main(String[] arg){

List list = new ArrayList<>();

try{

TreeUtils.toJson(list,"id","parentId","list",0);

}catch (Exception e){

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值