分享知識-快樂自己:N及分類(雙重迴圈、遞迴)實現
阿新 • • 發佈:2018-12-30
實現多級分類:
1、雙重 for 迴圈實現 N 及分類
/***
* 執行遍歷
*
* @param menus
* 所有許可權列表集合
* @param list
* 指定角色查詢到的 許可權Id
* @return
*/
@SuppressWarnings("unused")
private List<MenuFunction> menuFunction(List<MenuFunction> menus, List<Integer> list) {
// 中轉集合
List<MenuFunction> functions = null;
try {
functions = new ArrayList<MenuFunction>();
// 迴圈遍歷選單層級關係
// 迴圈遍歷
int a = 0;
int b = 0;
int c = 0;
for (MenuFunction item : menus) {
b = 0;
++c;
// 獲取pid
long pid = item.getPid();
System.out.println("外層---迴圈》》》\t" + (++a) + "\t當前PID:" + pid);
if (list.contains(item.getId().intValue())) {
item.setChecked(true);//
}
if (pid == 0) {
// 遍歷一級分類
functions.add(item);
} else {
System.out.println("******************************************");
for (MenuFunction innerCate : menus) {
++c;
/***
* 外層迴圈 pid 沒有的等於0 的話 獲取當前物件的 id 作為一級
*/
Long id = innerCate.getId();
System.out.println("內層---迴圈》》》\t" + (++b) + "\t當前ID:" + id);
if (id == pid) {
innerCate.getChildren().add(item);
break;
}
}
}
}
System.out.println("迴圈總記錄數為:》》》\t" + c);
} catch (Exception e) {
LOGGER.error("迴圈遍歷層級關係失敗!!!" + e);
}
return functions;
}
/***
* 去掉空的許可權
*
* @param list
* @return
*/
private List<MenuFunction> notNull(List<MenuFunction> list) {
List<MenuFunction> menusList = null;
try {
// 去掉空的許可權
menusList = new ArrayList<MenuFunction>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getChildren().size() != 0) {
menusList.add(list.get(i));
notNull(list.get(i).getChildren());
}
}
} catch (Exception e) {
LOGGER.error("去除空的許可權時意外出錯!!!" + e);
}
return menusList;
}
2、遞迴實現