How to use FileFilter interface in lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

A FileFilter is a functional interface from the "java.io" package. It can be used as the assignment target for a lambda expression or method reference. An instance of the FileFilter interface passed to the listFiles() method of the File class. FileFilter interface having one abstract method accept() and it tests whether or not the specified abstract pathname has included in a pathname list.

Syntax

@FunctionalInterface
public interface FileFilter

Example

import java.io.File;
import java.io.FileFilter;

public class FileFilterTest {
   public static void main(String[] args) {
      File dir = new File("C:/Program Files/Java/jdk1.8.0_211");

      File[] subDir = dir.listFiles((file) -> {    // lambda expression
            return file.isDirectory();
         }
      );
      for(File file : subDir) {
         System.out.println(file.getName());
      }
   }
}

Output

bin
include
jre
lib
raja
Published on 03-Jan-2020 09:36:48
Advertisements