スキップしてメイン コンテンツに移動

Java 8 Lambda Expression

I am very excited about new Java 8 features, especially lambda expression.
I am jealous that C# had lambda expression when it was introduced in C# 3.0 loooong time ago.
Let me show you a power of lambda expression by simple code example - FileFiter.
Why I choose this example? Well, I have been so frustrated that I always had to write a bit redundant code even if for very simple FileFilter.

Please see following example code. Hope the example attracts you...
package com.dukesoftware.io;

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

public class FileFilters {
    
    // legacy file filter - no lambda expression
    public static final FileFilter DIRECTORY_FILTER_BEFORE_JAVA8_NO_LAMBDA = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    };
    
    // basic lambda expression introduced since java 8
    public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_FIRST = (File pathname) -> { return pathname.isDirectory(); };
    
    // okay, you don't need braces for function body
    public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_NO_BRACES = (File pathname) -> pathname.isDirectory();
    
    // shortest version!
    public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_NO_TYPE = (pathname) -> pathname.isDirectory();

    // method reference version (oops, method reference version might be shorter than above one)
    public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_METHOD_REFERENCE = File::isDirectory;

}

If you would like to know more about Java 8, I strongly recommend to read "Java SE 8 for the Really Impatient".

I think this book is the best book for guide to Java 8!

コメント