菜单类
public static class Menu { Menu(String data) { String[] split = data.split(" "); this.id = Integer.valueOf(split[0]); this.name = split[1]; this.pid = Integer.valueOf(split[2]); } Integer id; String name; Integer pid; List<Menu> children; }
菜单数据
static String MENUS = "1 node1 0 ," + "2 node2 0 ," + "3 node3 0 ," + "4 node4 1 ," + "5 node5 1 ," + "6 node6 1 ," + "7 node7 2 ," + "8 node8 2 ," + "9 node9 3 ," + "10 node10 4 ," + "11 node11 4 ," + "12 node12 4 ," + "13 node13 5 ," + "14 node14 5 ," + "15 node15 6 ," + "16 node16 7 ," + "17 node17 7 ," + "18 node18 7 ," + "19 node19 8 ," + "20 node20 8 ," + "21 node21 9 ," + "22 node22 10 ," + "23 node23 10 ," + "24 node24 10 ," + "25 node25 11 ," + "26 node26 11 ," + "27 node27 12 ," + "28 node28 13 ," + "29 node29 13 ," + "30 node30 13 ," + "31 node31 14 ," + "32 node32 14 ," + "33 node33 15 ," + "34 node34 16 ," + "35 node35 16 ," + "36 node36 16 ," + "37 node37 17 ," + "38 node38 17 ," + "39 node39 18 ," + "40 node40 19 ," + "41 node41 19";
public static List<Menu> getMenus(String s) { String[] split = s.split(" ,"); List<Menu> menus = new ArrayList<>(); for (String s1 : split) { menus.add(new Menu(s1)); } return menus; }
两个循环出结果tree
public static void main(String[] args) { List<Menu> menus = getMenus(MENUS); Map<Integer, List<Menu>> map = new HashMap(); for (Menu menu : menus) { if (!map.containsKey(menu.getPid())) { map.put(menu.getPid(), new ArrayList<>()); } map.get(menu.getPid()).add(menu); } for (Menu menu : menus) { menu.setChildren(map.get(menu.getId())); } List<Menu> res = map.get(0); System.out.println(res); }
结果图
标签:map,搞定,菜单,String,menu,tree,menus,split,Menu From: https://www.cnblogs.com/LcxSummer/p/17319302.html