Skip to main content

Java 8 - Functional Interfaces

Greetings!

Functional interface is an interface which has only one abstract method. Runnable, Comparable, ActionListener are few existing examples.
interface with only one abstract method.
You can have many methods in the interface but should have only one abstract method.

To ensure that an interface has only one abstract method, Java8 comes with @FunctionalInterface annotation. It is not mandatory to have this, but with this compiler warns you when you break the contract.

We can avoid inner classes' and use lambda expression in place of these interfaces.

For an example we can create a thread like this;


Thread thread = new Thread(() -> System.out.println("Hello functional interface"));
thread.start();


Let's say we have fruits names and we need to print them according to given condition.
With prior to Java 8, we can do it like this;


public interface Testable {
    boolean test(String name);
}


import java.util.Arrays;
import java.util.List;

public class WorkerApp {

    public static void main(String[] args) {
        List fruits = Arrays.asList("Apple", "Java Plums", "Mango", "Banana");
        
        test(fruits, new Testable() {
            @Override
            public boolean test(String name) {
                return name.length() == 5;
            }
        });

        test(fruits, new Testable() {
            @Override
            public boolean test(String name) {
                return name.length() > 5;
            }
        });
    }
    
    private static void test(List fruits, Testable testable) {
        for (String name : fruits) {
            if (testable.test(name)) {
                System.out.printf("%s - test passed %n", name);
            }
        }
    }
}


Using lambda expressions we can simply this as;


    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Java Plums", "Mango", "Banana");

        test(fruits, (name) -> name.length() == 5);
        test(fruits, (name) -> name.length() > 5);
    }


Good thing is Java 8 comes with many useful functional interfaces so that we do not need to create our own. Have a look at the documentation.

Above code can be re-written in Java 8 as below;


import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Java8FirstApp {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Java Plums", "Mango", "Banana");

        test(fruits, (name) -> name.length() == 5);
        test(fruits, (name) -> name.length() > 5);
    }

    private static void test(List<String> names, Predicate<String> predicate) {
        for (String name : names) {
            if (predicate.test(name)) {
                System.out.printf("%s - test passed %n", name);
            }
        }
    }
}


clear and concise!!!


Comments