噗哩噼啦
2019-05-23 10:50
采纳率: 0%
浏览 561
已结题

java list 内递归构建树,效率很差,如果remove节点报ConcurrentModificationException

递归调用循环次数太多,求救,效率很慢
list大小3000+,
当想着循环时发现父节点挂接到父节点的时候,减小list大小来减少循环次数,却报错,
希望能得到帮助,如何优化,重写?
代码中只能得到根节点的ID
代码原图

/**
     * @param aynpAll 所有数据
     * @param checkId 根节点ID
     * @return
     */
    private static AynpTree getAyTree(final List<TAynp> aynpAll, final String checkId) {
        List<AynpTree> dataList = aylistToAyTreeList(aynpAll); //转换树对象
        //根节点
        List<AynpTree> treeRootList = (List<AynpTree>) CollectionUtils.select(dataList, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                AynpTree ay = (AynpTree) object;
                if (StringUtils.isBlank(checkId)) {
                    return StringUtils.isBlank(ay.getPid());
                } else {
                    return StringUtils.equals(ay.getId(), checkId);
                }
            }
        });
        //开始递归
        getTreeNode(dataList, treeRootList);
        return treeRootList.get(0);
    }
    /**
     * 递归调用
     * @param dataList全部数据集合
     * @param treeRootList
     */
    private static void getTreeNode(List<AynpTree> dataList, List<AynpTree> treeRootList) {
        for (AynpTree treeRoot : treeRootList) {
            List<AynpTree> children = new ArrayList<AynpTree>();
            //            Iterator<AynpTree> iterator = dataList.iterator();
            ListIterator<AynpTree> listIterator = dataList.listIterator();
            while (listIterator.hasNext()) {
                AynpTree data = (AynpTree) listIterator.next();
                a++;
                if (StringUtils.equals(treeRoot.getId(), data.getPid())) {
                    children.add(data);
                    listIterator.remove();
                    getTreeNode(dataList, children);
                }
            }
            treeRoot.setChildren(children);
        }
    }
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

相关推荐 更多相似问题