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

see if all elements in a Java collection end with one of the members of a List

我在 Java 11 中有一个文件列表。 如果所有文件都以集合中列出的扩展名之一结尾,我想签入单行解决方案。 所以我有 List<File> filesInOutputList<String> wantedExtensions 包含元素“.html”和“.png”。 我想检查 filesInOutput 中的所有文件是否以“.html”或“.png”结尾,如果 filesInOutput 包含以“.pdf”结尾的文件,例如,我想 return 错误的。 我已经完成了这段代码:

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()... 来实现这一点,但事实上我们承认的扩展在一个集合中使得这个解决方案更加困难。

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

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

Streams 方便地为我们提供了一个 allMatch 运算符

仍然是一个双循环,但是一个 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);

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