Functional Interfaces In Java 8
This article was published at http://midhunhk.github.io/2016/08/03/java-8-functional-interfaces/
Functional Interface
A Functional Interface is an interface that has only one abstract method. Lambdas help us get rid of boilerplate code and remove use of anonymous inner classes.
See below for examples with a custom interface and see how code with and without lambda expressions look.
Lets see the how this lambda expression really works.
(name, age) -> System.out.println(“Hello “ + name + “, you are “ + age + “ old”);
Here, userInfo has only one method printInfo(String name, Integer age). This is all information for the compiler to create an anonymous inner class. This expression has two parts separated by a -> operator. The first part, (name, age) represents the parameter list for the method and the code after -> is the body for the method.
There is a steep learning curve when it comes to lambda expressions for experienced Java developers, especially if they are not familiar with this concept in javascript or any other languages. Once the basic principles are clear, it is easy to follow.
Closures in JavaScript
The below code is the above example written in javascript. Here the object userInfo is a function that can be invoked by passing parameters
Predicates
Predicate is a Functional Interface included in Java 8 which represents a boolean valued function. It has a boolean test(T t) method which accepts an object as parameter and returns a boolean result. Check the below example and see if you are able to figure how it works
Further Reading
https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html