查看Java集合中的所有元素是否都以List的一个成员结束



我有一个Java 11中的文件列表。如果所有文件都以集合中列出的某个扩展名结尾,我想签入一个单行解决方案。所以我有List<File> filesInOutputList<String> wantedExtensions具有元件";。html";和";。png";。我想检查filesInOutput中的所有文件是否都以"结尾;。html";或";。png";,如果filesInOutput包含以";。pdf";,例如,我想返回false。我已经做了这个代码:

boolean allMatch = true;
for(File fileInOutput : filesInOutput) {
boolean matches = false;
for(String wantedExtension : wantedExtensions) {
matches = fileInOutput.getPath().endsWith(wantedExtension);
if (matches) {
break;
}
}
if (!matches) {
allMatch = false;
break;
}
}
return allMatch;

理想情况下,我希望在一行解决方案中使用filesInOutput.stream().filter()...来实现这一点,但我们承认的扩展在一个集合中这一事实使该解决方案更加困难。

仍然是双循环,但却是lambda:(

Set<String> extensions = new HashSet<>(wantedExtensions);
filesInOutput.stream()
.map(file -> file.getPath())
.allMatch(filePath ->
extensions.stream()
.anyMatch(filePath::endsWith));

你当然想要这样的东西:

Set<String> extensions = new HashSet<>(wantedExtensions);
filesInOutput.stream()
.map(file -> getExtension(file.getPath()))
.allMatch(extensions::contains);

你只需要想出一个方法来获得扩展。如果您进行搜索,您可以使用regex或其他答案中的方法在SO上找到一些选项。

我自己还没有运行过,也许这可以改进,但我认为这应该有效,不是吗?

Boolean allMatch = filesInOutput.stream().map(file -> file.getName().substring(file.getName().lastIndexOf("."))).allMatch(name -> wantedExtensions.contains(name));

流方便地为我们提供了allMatch算子

最新更新