集合不能一边遍历一边删除问题处理记录(遍历的同时删除多条元素)

直接用for遍历删除会抛出异常
改用Iterator迭代器实现遍历删除

/**
     * 获取所有模型组
     * @param tables
     * @return
     */
    public List<Set<String>> getDeployGroups(List<String> tables){
        List<Set<String>> deployGroups = new ArrayList<>();
        Iterator<String> iterator = null;
        iterator = tables.iterator();
        while(iterator.hasNext()) {
            String table = iterator.next();
            List<GoDataModelTablePosition> positions = new ArrayList<>();
            GoDataModel goDataModel = baseMapper.selectOne(new QueryWrapper<GoDataModel>().eq("warehouse_table_name",table));
            Set<String> deployRelations  = new HashSet<>();
            if(goDataModel!=null){//模型表 依赖&被依赖
                //该模型依赖了哪些表
                positions = goDataModelTablePositionMapper.selectList(new QueryWrapper<GoDataModelTablePosition>().eq("model_id", goDataModel.getId()));
                Set<String> deployTables = positions.stream().map(GoDataModelTablePosition::getTableSourceName).collect(Collectors.toSet());
                deployRelations.addAll(deployTables);
                //哪些模型依赖的该模型
                List<GoDataModelTablePosition> rPositions = goDataModelTablePositionMapper.selectList(new QueryWrapper<GoDataModelTablePosition>().eq("table_source_name", goDataModel.getWarehouseTableName()));
                Set<String> tablesDeploy = rPositions.stream().map(GoDataModelTablePosition::getTableName).collect(Collectors.toSet());
                deployRelations.addAll(tablesDeploy);
            }else{//源表 只有被依赖
                //哪些模型依赖的该表
                positions = goDataModelTablePositionMapper.selectList(new QueryWrapper<GoDataModelTablePosition>().eq("table_source_name", table));
                Set<String> tablesDeploy = positions.stream().map(GoDataModelTablePosition::getTableName).collect(Collectors.toSet());
                deployRelations.addAll(tablesDeploy);
            }
            //存在依赖关系的表
            if(!CollectionUtils.isEmpty(deployRelations)){
                Set<String> mateGroup = new HashSet<>();
                mateGroup.add(table);
                for (String deployTable : deployRelations) {
                    mateGroup.add(deployTable);
                    getDeployGroup(deployTable,mateGroup);
                }
                //将模型组放入集合中
                deployGroups.add(mateGroup);
                //将已加入分组的模型移除,避免分组重复
                for (String groupTable : mateGroup) {
                    if(tables.contains(groupTable)){
                        tables.remove(groupTable);
                    }
                }
                iterator = tables.iterator();
            }else{
                continue;
            }

        }
        return (List) deployGroups.stream().distinct().collect(Collectors.toList());
    }

你可能感兴趣的:(笔记,java,集合遍历删除多条元素)