/**
* 重命名重复的文件名
*
* @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;
}
![]()