/** * 根据租户id获取部门树状结构 * @param tenantId * @return */ @GetMapping("getDeptTreeList") public R getDeptTreeList(String tenantId){ List<Dept>list=deptUserUtil.getDeptList(tenantId); System.out.println("根据租户id获取部门树状结构list================"+list); //实体类转map List<Map<String,Object>> listMap=EntityConvertMap(list); //把带有父子机构的数据变成treelist形式 List<Map<String,Object>>treeList=getTreeList("id","parentId","children", listMap); System.out.println("根据租户id获取部门树状结构treeList================"+treeList); return R.data(treeList); } //list实体类转换成map public static List<Map<String,Object>> EntityConvertMap(List<Dept> list){ List<Map<String,Object>> l = new LinkedList<>(); try { for(Dept t : list){ Map<String,Object> map = new HashMap<>(); Method[] methods = t.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("get")) { String name = method.getName().substring(3); name = name.substring(0, 1).toLowerCase() + name.substring(1); Object value = method.invoke(t); map.put(name,value); } } l.add(map); } } catch (Exception e) { e.printStackTrace(); } return l; } //把带有父子机构的数据变成treelist形式 public static List<Map<String, Object>> getTreeList(String id, String pid, String children, List<Map<String, Object>>list) { //给list的每一项加一个子项 for(int i=0;i<list.size();i++) { list.get(i).put(children, new ArrayList<Map<String, Object>>()); list.get(i).put("id",list.get(i).get("id").toString()); list.get(i).put("parentId",list.get(i).get("parentId").toString()); //managerUser list.get(i).put("managerUser",list.get(i).get("managerUser").toString()); } System.out.println("把带有父子机构的数据变成treelist形式list==============="+list); List<Map<String, Object>>treelist=new ArrayList<Map<String, Object>>(); for(Map<String, Object> outmap:list) { //System.out.println("把带有父子机构的数据变成outmap==============="+outmap); for(Map<String, Object> inmap:list) { String outid=outmap.get(id).toString(); String inpid=inmap.get(pid).toString(); if(outid.equals(inpid)) { List<Map<String, Object>>maplist=(ArrayList) outmap.get(children); maplist.add(inmap); } } String prid=outmap.get(pid).toString(); if(!Func.isEmpty(prid)&& prid.equals("0")) { treelist.add(outmap); } } return treelist; }
原文:https://www.cnblogs.com/xianz666/p/13553451.html