您好,登錄后才能下訂單哦!
本篇文章為大家展示了java中怎么遞歸部門(mén)樹(shù),內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
package com.ytx.demo.tree; import java.util.ArrayList; import java.util.List; public class Department { private int id; private String name; private int parentId; private List<Department> children = new ArrayList<Department>(); public Department(int id, String name, int parentId) { this.id = id; this.name = name; this.parentId = parentId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public List<Department> getChildren() { return children; } public void setChildren(List<Department> children) { this.children = children; } }
package com.ytx.demo.tree; import java.util.ArrayList; import java.util.List; public class DempartmentThree { public static void main(String[] args) { List<Department> departmentList = new ArrayList<>(); departmentList.add(new Department(1, "研發(fā)部門(mén)", 0)); departmentList.add(new Department(2, "研發(fā)團(tuán)隊(duì)1", 1)); departmentList.add(new Department(3, "研發(fā)團(tuán)隊(duì)2", 1)); departmentList.add(new Department(4, "財(cái)務(wù)部門(mén)", 0)); departmentList.add(new Department(5, "財(cái)務(wù)A部門(mén)", 4)); departmentList.add(new Department(6, "財(cái)務(wù)B部門(mén)", 4)); departmentList.add(new Department(7, "財(cái)務(wù)A部門(mén)團(tuán)隊(duì)1", 5)); departmentList.add(new Department(8, "財(cái)務(wù)A部門(mén)團(tuán)隊(duì)2", 5)); departmentList.add(new Department(9, "財(cái)務(wù)B部門(mén)團(tuán)隊(duì)1", 6)); departmentList.add(new Department(10, "財(cái)務(wù)B部門(mén)團(tuán)隊(duì)2", 6)); List<Department> listTree = getThree(departmentList,0); System.out.println(listTree); } private static List<Department> getThree(List<Department> list,int parentId){ //獲取所有子節(jié)點(diǎn) List<Department> childTreeList = getChildTree(list,parentId); for (Department dept:childTreeList) { dept.setChildren(getThree(list,dept.getId())); } return childTreeList; } private static List<Department> getChildTree(List<Department> list,int id){ List<Department> childTree = new ArrayList<>(); for (Department dept:list) { if(dept.getParentId() == id){ childTree.add(dept); } } return childTree; } }
上述內(nèi)容就是java中怎么遞歸部門(mén)樹(shù),你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。