Java中如何检测无扩展名的文件名是否存在于字符串列表并统计次数
实现方案
核心逻辑是先截取每个文件名最后一个.之前的部分(无扩展名的文件名直接使用原名称),再和目标文件名匹配即可,以下给出三种不同场景的实现方案:
工具方法(所有方案通用)
// 提取无扩展名的文件名 private static String getFileNameWithoutExt(String fileName) { int dotIndex = fileName.lastIndexOf('.'); // 不存在后缀直接返回原文件名 return dotIndex == -1 ? fileName : fileName.substring(0, dotIndex); }
注意不要使用indexOf('.')截取扩展名,避免文件名本身包含.的场景下截取错误
方案1:基础遍历实现(兼容Java 8以下版本)
适合所有Java版本,逻辑直观易修改:
// 判断指定无扩展名文件名是否存在 public static boolean existsWithoutExt(List<String> fileList, String targetName) { for (String fileName : fileList) { if (getFileNameWithoutExt(fileName).equals(targetName)) { return true; } } return false; } // 统计指定无扩展名文件名出现次数 public static int countWithoutExt(List<String> fileList, String targetName) { int count = 0; for (String fileName : fileList) { if (getFileNameWithoutExt(fileName).equals(targetName)) { count++; } } return count; }
调用示例:
// 针对你给出的示例列表 boolean isExist = existsWithoutExt(list, "filename2"); // 返回true int count = countWithoutExt(list, "filename2"); // 返回3
方案2:Java 8+ Stream流简洁实现
不需要额外封装方法,直接用Stream完成需求:
// 判断是否存在 boolean isExist = list.stream() .map(YourClass::getFileNameWithoutExt) .anyMatch("filename2"::equals); // 统计出现次数 long count = list.stream() .map(YourClass::getFileNameWithoutExt) .filter("filename2"::equals) .count();
注意把YourClass替换为你实际存放工具方法的类名
方案3:多次查询场景预处理方案
如果需要频繁查询不同文件名的存在性或次数,建议提前生成统计Map,后续查询时间复杂度为O(1):
import java.util.function.Function; import java.util.stream.Collectors; // 预生成 无扩展文件名->出现次数 的统计映射 Map<String, Long> fileNameCountMap = list.stream() .map(YourClass::getFileNameWithoutExt) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // 后续查询直接从Map取值即可 long filename2Count = fileNameCountMap.getOrDefault("filename2", 0L); boolean isFilename2Exist = filename2Count > 0;
特殊场景适配
如果你的列表中存储的是带路径的文件全路径,需要先提取纯文件名再截取后缀,修改工具方法即可:
import java.io.File; private static String getFileNameWithoutExt(String fullPath) { String pureName = new File(fullPath).getName(); int dotIndex = pureName.lastIndexOf('.'); return dotIndex == -1 ? pureName : pureName.substring(0, dotIndex); }
内容的提问来源于stack exchange,提问作者pharo
相关产品推荐
相关产品推荐

