文件名重命名算法

 

复制代码
 /**
     * 重命名重复的文件名
     *
     * @param fileNameList 文件名列表
     * @return重命名后的文件名列表
     */
    private static List<String> getNoRepeatFileNameList(List<String> fileNameList) {
        //按文件名分组找到重复的文件名,使用LinkedHashMap保存分组结果,保证文件名顺序基本不变(重命名的除外)
        Map<String, List<String>> fileNameMap = fileNameList.stream()
                .collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<String>> entry : fileNameMap.entrySet()) {
            List<String> valueList = entry.getValue();
            if (valueList.size() > 1) {
                int index = 0;
                for (String name : valueList) {
                    String newName = String.format("%s(%s)%s", name.substring(0, name.lastIndexOf(".")), index + 1, name.substring(name.lastIndexOf(".")));
                    valueList.set(index, newName);
                    index++;
                }
            }
        }

        // 遍历原始列表,取新文件名
        List<String> newFileNameList = new ArrayList<>();
        for (String fileName : fileNameList) {
            //从map中获取新文件名(依次取值)
            List<String> valueList = fileNameMap.get(fileName);
            newFileNameList.add(valueList.remove(0));
        }

        return newFileNameList;
    }
复制代码

 

 

posted @   追极  阅读(92)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2018-03-20 java lock锁住特定对象
点击右上角即可分享
微信分享提示