/** * 设置树对象的以ID为索引的Map * * @param forest 树对象的列表 * @param treeIndexMap 所对应的索引Map */ public static <V extends TreeNodeBean> void setTreeIndexMap( List<TreeNode<V>> forest, Map<String, TreeNode<V>> treeIndexMap) { if (forest == null || forest.size() == 0) return; for (TreeNode<V> tn : forest) { treeIndexMap.put(tn.getId(), tn); if (!tn.isLeaf()) TreeUtils.setTreeIndexMap(tn.getChildren(), treeIndexMap); } }
/** * 重组树,根据idc中的结点id,重组forest中的树,新的树包括仅包括idc中所有id结点的所有祖宗结点和子结点 * * @param forest 树对象的列表,此对象是需要重组树的全集 * @param idc 结点id的Collection * @return 重组后的树,此树是原树的一个重组后的拷贝 * @throws CloneNotSupportedException */ public static <V extends TreeNodeBean> List<TreeNode<V>> restructureTree( List<TreeNode<V>> forest, Collection<String> idc) throws CloneNotSupportedException { if (forest == null || forest.size() == 0) return null; if (idc == null || idc.size() == 0) return null; List<TreeNode<V>> restructureForest = new ArrayList<TreeNode<V>>(); idc = TreeUtils.distinctList(idc); for (String id : idc) { for (TreeNode<V> tn : forest) { TreeNode<V> _ftn = tn.getId().equals(id.trim()) ? tn : tn.findNode(id.trim()); // 在原树中查找是否有id结点 if (_ftn != null) { // 若有 TreeNode<V> ctn = _ftn.clone(); // 以此id为根的树的克隆 boolean hasDeal = false; for (TreeNode<V> rn : restructureForest) { TreeNode<V> _rftn = rn.findNode(ctn.getId()); hasDeal = (_rftn != null); } while (!hasDeal) { if (!_ftn.isRoot()) _ftn = _ftn.getParent(); else { restructureForest.add(ctn); hasDeal = true; } if (!hasDeal) { for (TreeNode<V> rn : restructureForest) { // 查找合适的位置插入 TreeNode<V> _rftn = rn.getId().equals(_ftn.getId()) ? rn : rn.findNode(_ftn.getId()); if (_rftn != null) { _rftn.addChild(ctn); hasDeal = true; } } } if (!hasDeal) { // 造上级结点 TreeNode<V> _ptn = new TreeNode<V>(_ftn.getTnEntity()); _ptn.addChild(ctn); ctn = _ptn; } } } } } return restructureForest; }