How to use FileFilter interface in lambda expression in Java?


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

Updated on: 13-Jul-2020

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements