您好,登錄后才能下訂單哦!
本篇文章為大家展示了java中怎么遞歸部門樹,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
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, "研發部門", 0)); departmentList.add(new Department(2, "研發團隊1", 1)); departmentList.add(new Department(3, "研發團隊2", 1)); departmentList.add(new Department(4, "財務部門", 0)); departmentList.add(new Department(5, "財務A部門", 4)); departmentList.add(new Department(6, "財務B部門", 4)); departmentList.add(new Department(7, "財務A部門團隊1", 5)); departmentList.add(new Department(8, "財務A部門團隊2", 5)); departmentList.add(new Department(9, "財務B部門團隊1", 6)); departmentList.add(new Department(10, "財務B部門團隊2", 6)); List<Department> listTree = getThree(departmentList,0); System.out.println(listTree); } private static List<Department> getThree(List<Department> list,int parentId){ //獲取所有子節點 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; } }
上述內容就是java中怎么遞歸部門樹,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。