1. 程式人生 > >選單樹的生成程式碼

選單樹的生成程式碼

public class MenuService implements IMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;


    public List<SysMenuDTO> queryAll(){
        String lang = LocaleContextHolder.getLocale().getLanguage();
        List<SysMenuDTO> rspMenuDTOList = new ArrayList();
        List<SysMenu> sysMenuAllList = sysMenuMapper.queryAll();
        if( sysMenuAllList == null || sysMenuAllList.size() == 0 ){
            return rspMenuDTOList;
        }

        //根節點 ,父節點分類
        Iterator iterator = sysMenuAllList.iterator();
        Map<Long,List<SysMenuDTO>> map = new HashMap<Long,List<SysMenuDTO>>();
        while(iterator.hasNext()){
            SysMenu sysMenu = (SysMenu)iterator.next();
            Long parentId = sysMenu.getParentId();
            List<SysMenuDTO> list = map.get(parentId)==null?new ArrayList<SysMenuDTO>():map.get(parentId);
            SysMenuDTO sysMenuDTO = new SysMenuDTO();
            BeanUtility.copyBean(sysMenuDTO,sysMenu);
            if(lang.equals("zh")){
                sysMenuDTO.setName(sysMenu.getCnName());
            }else {
                sysMenuDTO.setName(sysMenu.getEnName());
            }
            list.add(sysMenuDTO);
            map.put(parentId,list);
        }
        List<SysMenuDTO> rootList = map.get(0L);

        //查詢子節點
        for(int i=0; i<rootList.size();i++){
            findChildren(map,rootList.get(i));
        }

        return rootList;
    }


    public void findChildren( Map<Long,List<SysMenuDTO>> allMap,SysMenuDTO parentSysMenu){
        List<SysMenuDTO> childList = allMap.get(parentSysMenu.getId());
        if(childList!=null && childList.size()>0){
            parentSysMenu.setChildren(childList);
            for(int i=0;i<childList.size();i++){
                findChildren(allMap,childList.get(i));
            }
        }

    }

}