java版本:
1 /** 2 * 通过集合方式生成树 3 * @param list 4 * @return 5 */ 6 public static Map<String, Object> getTreeByColl(List<Menu> list) { 7 Map<String, Object> resmap=new HashMap<>(); 8 Map<Integer, Menu> map; 9 List<Menu> treelist= new ArrayList<>(); 10 11 if (null==list||list.isEmpty()){ 12 return null; 13 } 14 map = list.stream().collect(Collectors.toMap(Menu::getId, a -> a,(k1, k2)->k1)); 15 /*List<Map.Entry<Integer, Menu>> listMap = new ArrayList<Map.Entry<Integer, Menu>>(map.entrySet()); 16 Collections.sort(listMap, new Comparator<Map.Entry<Integer, Menu>>() { 17 public int compare(Map.Entry<Integer, Menu> o1, Map.Entry<Integer, Menu> o2) { 18 return o2.getKey().compareTo(o1.getKey()); 19 } 20 });*/ 21 // 将list集合对象转换为json的字符串 22 // 如果id是父级的话就放入tree中treelist 23 for (Menu menu : list) { 24 if (null==map.get(menu.getParId())) { 25 treelist.add(menu); 26 } else { 27 // 子级通过父id获取到父级的类型 28 Menu parent = map.get(menu.getParId()); 29 // 父级获得子级,再将子级放到对应的父级中 30 parent.addChildren(menu); 31 } 32 } 33 34 35 resmap.put("data",treelist); 36 return resmap; 37 }
js版本:
const nest = (items, id = null, link = 'parent_id') =>items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }));