java 樹形物件工具類封裝
阿新 • • 發佈:2018-12-25
基礎的樹形物件:
import java.io.Serializable; import java.util.List; /** * treegrid樹形表格基礎物件,後續的該型別的物件均繼承該物件 * */ public class BaseTreeGrid implements Serializable{ /** * */ private static final long serialVersionUID = -9189631784252440402L; public String id;//節點id public String parentId;//節點父id public String iconCls = "folder";//節點樣式,預設即可 public Boolean leaf = true;//是否為葉子節點,true表示是葉子節點,false表示不是葉子節點 public Boolean expanded = true; //是否展開,預設true,展開 public List<BaseTreeGrid> children;//孩子節點 public BaseTreeGrid() { } public BaseTreeGrid(String id, String parentId) { this.id=id; this.parentId=parentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getIconCls() { return iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } public Boolean getLeaf() { return leaf; } public void setLeaf(Boolean leaf) { this.leaf = leaf; } public Boolean getExpanded() { return expanded; } public void setExpanded(Boolean expanded) { this.expanded = expanded; } public List<BaseTreeGrid> getChildren() { return children; } public void setChildren(List<BaseTreeGrid> children) { this.children = children; } }
import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSONArray; import com.eshore.common.ext.BaseTreeGrid; /** * 將記錄list轉化為樹形list * 基於BaseTreeGid類的轉換 * */ public class TreeUtils { /** * 格式化list為樹形list * @param list * @param falg true 表示全部展開,其他 表示不展開 * @return */ public static <T extends BaseTreeGrid> List<T> formatTree(List<T> list, Boolean flag) { List<T> nodeList = new ArrayList<T>(); for(T node1 : list){ boolean mark = false; for(T node2 : list){ if(node1.getParentId()!=null && node1.getParentId().equals(node2.getId())){ node2.setLeaf(false); mark = true; if(node2.getChildren() == null) { node2.setChildren(new ArrayList<BaseTreeGrid>()); } node2.getChildren().add(node1); if (flag) { //預設已經全部展開 } else{ node2.setExpanded(false); } break; } } if(!mark){ nodeList.add(node1); if (flag) { //預設已經全部展開 } else{ node1.setExpanded(false); } } } return nodeList; } public static void main(String[] args) { List<BaseTreeGrid> list = new ArrayList<BaseTreeGrid>(); BaseTreeGrid root1 = new BaseTreeGrid(); root1.setId("1"); BaseTreeGrid child1 = new BaseTreeGrid(); child1.setId("11"); child1.setParentId("1"); BaseTreeGrid child11 = new BaseTreeGrid(); child11.setId("111"); child11.setParentId("11"); BaseTreeGrid root2 = new BaseTreeGrid(); root2.setId("2"); BaseTreeGrid child2 = new BaseTreeGrid(); child2.setId("21"); child2.setParentId("2"); list.add(root1); list.add(child1); list.add(child11); list.add(root2); list.add(child2); List<BaseTreeGrid> treelist = formatTree(list, false); String json = JSONArray.toJSONString(treelist); System.out.println(json); } }