【问题标题】:how to change the below code to lamba method reference如何将以下代码更改为 lambda 方法参考
【发布时间】:2018-05-24 14:42:10
【问题描述】:

嗨,下面是我从提供的文件夹路径中获取文件列表的逻辑,下面的 sn-p 正在工作, 但是有声纳问题要更改代码以遵循带有方法引用的 lambda 表达式。 任何帮助表示赞赏。

public static File[] getFileName(String folderPath) {
    File[] fileEntry = null;
    File folder = new File(folderPath);
    fileEntry = folder.listFiles(new FileFilter() { 
      @Override
      public boolean accept(File pathname) {
        return pathname.isFile();
      }
    });
    return fileEntry;
  }

提前致谢

【问题讨论】:

    标签: lambda filefilter


    【解决方案1】:

    IntelliJ IDEA 可以进行快速修复等代码优化。

    Lambda 形式:

    public static File[] getFileName(String folderPath) {
        File[] fileEntry;
        File folder = new File(folderPath);
        fileEntry = folder.listFiles(pathname -> pathname.isFile());
        return fileEntry;
    }
    

    最短的形式是:

    public static File[] getFileName(String folderPath) {
        return new File(folderPath).listFiles(File::isFile);
    }
    

    【讨论】:

    • 感谢您的快速响应 tkruse,它真的很有帮助,想添加一些 cmets,如 public static File[] getFileName(String folderPath) { File[] fileEntry;文件夹 = 新文件(文件夹路径); fileEntry = folder.listFiles(路径名 -> 路径名.isFile());返回文件入口;这些代码即使在转换为 lambda 表达式后也会产生声纳问题,已经尝试过了,但最短的形式更明智,我觉得相对于声纳覆盖范围。
    • 当然,第一种形式可能会给您其他警告。 Shortest 应该没有警告,否则告诉我们警告。如果我的回答没问题,请随意点击左侧的接受按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多