【问题标题】:Is it possible to use file array in lambda expression and let it update?是否可以在 lambda 表达式中使用文件数组并让它更新?
【发布时间】:2021-01-13 04:41:44
【问题描述】:

我正在使用的块在 lambda 中对字符串数组列表运行 foreach 循环。表达式试图过滤掉与模式匹配的文件列表并将其存储在文件数组中。

这里的问题是数组列表将运行 n 次,它会多次更新文件数组。 我需要一个正确的解决方案,它允许使用 lambda,允许在一个路径中查找所有模式并允许将其存储在一个文件数组中。

我使用的代码是错误的,

File[] fileList2 = null;
ArrayList<String> listOfLines = new ArrayList<>();
String line = bufReader.readLine();
while (line != null) 
{
  listOfLines.add(line); 
  line = bufReader.readLine(); 
}
bufReader.close();
listOfLines.forEach((n) -> 
{
    fileList2 = new File("directory/path/").listFiles(new FilenameFilter()
    {
        public boolean accept(File arg0, String arg1)
        {
            boolean result;
            if(arg1.contains(n))
                result=true;
            else
                result=false;
            return result;
        }
    });
});

我的方法不正确,因为每次迭代fileList2都会更新,这不是必需的。

由于同样的原因,我也遇到了错误

在封闭范围内定义的局部变量 fileList2 必须是 final 或有效 final

【问题讨论】:

    标签: java lambda foreach


    【解决方案1】:

    您遇到了错误,因为每次调用 lambda 时,fileList2 都设置为不同的值,将 foreach 部分重写为正常循环可以更好地揭示正在发生的事情

    File[] fileList2 = null;
    ...
    for (String line : listOfLines) {
        fileList2 = new File("directory/path/").listFiles(...
        ...
    }
    

    如您所见,fileList2 仅设置为与 listOfLines 中的最后一个条目有关的文件数组。

    顺便说一句,你可以改变

    boolean result;
    if(arg1.contains(n))
        result=true;
    else
        result=false;
    return result;
    

    到一行代码...

    return arg1.contains(n);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 2017-04-19
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多