gpt4 book ai didi

java - 考虑 for-each 循环中 lambda 表达式中的两种情况

转载 作者:太空宇宙 更新时间:2023-11-04 10:50:37 26 4
gpt4 key购买 nike

作为练习,我决定学习 Java 中的 lambda 表达式。我想重写我发现笨拙且冗长的旧代码。它检查命令行参数是否是(1)文件路径或(2)目录路径。在(1)场景中,它将命令行参数传递给方法。在 (2) 场景中,它检查给定目录中是否有 *.pdf 文件,然后(并且只有在那时)传递每个文件的路径。我的代码如下:

File file = new File(args[0]);
if (file.exists()) {
if (!file.isDirectory()) {
modifyPdf(args[0]);
}
else {
File[] files = new File(args[0]).listFiles((FileFilter) new WildcardFileFilter("*.pdf"));
if (files != null) {
for (File f : files) {
modifyPdf(f);
}
}
}

}

我编写了一个处理 (1) 场景的 lambda 表达式。但是,我不知道如何在一个 lambda 表达式中考虑 (1) 和 (2) 场景。我尝试将代码更改为 lambda 表达式,如下所示:

for (Path path1 : Files.newDirectoryStream(Paths.get(args[0]), path ->
Files.isRegularFile(path)
&& path.toString().endsWith(".pdf"))) {
Class.meth(path1);
}

最佳答案

试试这个:

private void run() throws Exception
{
Path rootDir = Paths.get("data");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");

Files.walk(rootDir)
.filter(matcher::matches)
.forEach(this::modifyPdf);
}

private void modifyPdf(Path p) {
// Some code here...
}

关于java - 考虑 for-each 循环中 lambda 表达式中的两种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com