MenuTreeUtil選單樹形遞迴工具類
阿新 • • 發佈:2020-10-28
import com.aaa.controller.vm.MenuVM; import com.aaa.entity.Menu; import java.util.ArrayList; import java.util.List; /** * 組裝選單樹工具類 * Created by cws * @author Administrator */ public class MenuTreeUtil { public static MenuVM getTree(List<Menu> list) { //判斷是否有獲取到資料 if (list == null || list.size() < 1) { return null; } return buildTree(getRoot(list), list); } private static MenuVM buildTree(MenuVM pnode, List<Menu> nodes) { List<MenuVM> childs = new ArrayList<>(); for (Menu tmp : nodes) { if (pnode.getId().equals(tmp.getParentId())) { childs.add(new MenuVM(tmp)); } } //二次遞迴遍歷子節點 if (childs.size() > 0) { pnode.setSubMenu(childs); for (MenuVM ptmp : childs) { buildTree(ptmp, nodes); } } return pnode; } /** * 獲取一級目錄 * * @param list */ private static MenuVM getRoot(List<Menu> list) { for (Menu po : list) { if ("#".equals(po.getParentId())) { return new MenuVM(po); } } return null; } /** * @param list */ public static List<MenuVM> getMenu(List<Menu> list) { //判斷是否有獲取到資料 if (list == null || list.size() < 1) { return null; } return getTree(list) == null ? null : getTree(list).getSubMenu(); } }