简体   繁体   English

什么是正确的 lambda 这个内部 class

[英]what is the right lambda for this inner class

I have following code:我有以下代码:

  private List<String> searchFolder(File tempDirFile) {
            List<String> listFile;
            listFile = Arrays.asList(tempDirFile.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.contains(type);
                }
            }));
            return listFile;
        }

SonarLint tells me to "Make this anonymous inner class a lambda". SonarLint 告诉我“让这个匿名内部 class 成为 lambda”。 So this所以这

new FilenameFilter(){.....}新文件名过滤器(){.....}

is supposed to be "converted" into a lambda.应该被“转换”成 lambda。 I looked up cases and scenarios, but wasn't able to find a solution for this specific case I have here.我查找了案例和场景,但无法为我在这里找到的这个特定案例找到解决方案。

As requestedd by OP: FilenameFilter is a FunctionalInterface it has only one abstract method and it can be implemented with a lambda that match its signature and java compiler will infer the type:根据 OP 的要求: FilenameFilter 是一个FunctionalInterface它只有一个抽象方法,可以使用与其签名匹配的 lambda 实现,并且 java 编译器将推断类型:

Arrays.asList(tempDirFile.list((dir, name) -> name.contains(type)));

Edit: the @FunctionalInterface annotation is optional you can create lambda for any interface with only one abstract method even if not annotated with it.编辑: @FunctionalInterface注释是可选的,即使没有注释,您也可以为任何只有一个抽象方法的接口创建 lambda。

Edit 2: More about lambda expression https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html Edit 2: More about lambda expression https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM