Java 8 - FileFilter example using Lambda expression

Posted on November 23, 2016


java.io.FileFilter interface is a functional interface and annotated by @FunctionalInterface in java 8.

In this example, I will show you how we can use lambda expression to list name of subdirectories using FileFilter.

LambdaFileFilterExample.java

package com.boraji.tutorial.lambda;

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

/**
 * @author imssbora
 */
public class LambdaFileFilterExample {
	public static void main(String[] args) {
		File dir = new File("C:/Program Files/Java/jdk1.8.0_71");

		// Filter sub-directories using anonymous class
		File[] subDirs1 = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.isDirectory();
			}
		});

		System.out.println("-------------Using anonymous class------------");
		for (File file : subDirs1) {
			System.out.println(file.getName());
		}

		// Filter sub-directories using Lambda expression
		File[] subDirs2 = dir.listFiles((file)->{return file.isDirectory();});
		System.out.println("-------------Using Lambda Expression------------");
		for (File file : subDirs2) {
			System.out.println(file.getName());
		}
	}
}

Output

-------------Using anonymous class------------
bin
db
include
jre
lib
-------------Using Lambda Expression------------
bin
db
include
jre
lib