Pages

Thursday, February 6, 2014

Functional interface and Lambda in Java 8

In this post, we'll see what is a functional interface in Java 8, what its use in Lambda expression and how Lambda expression is useful with detailed examples. Before that you should have an idea of static and default method in interface.

Runnable is one of the interface that we discussed in this post is used by every java programmer. What is so special in Runnable interface is that it has only one abstract method declared in their interface definition. Such interface of this type are ActionListener, Callable and Comparator.

Functional Interface"An interface is considered a functional interface if it contains one and only one abstract method with no default implementation".Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.Example : java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable.Such functional interfaces are leveraged for use with lambda expressions.public interface Comparator<T>is also a functional interface but question is that it declared two abstract method but why it is still function interface? one of these equals() which has signature equal to public method in Object class.As per definition, "If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere."Lambda (λ) motivationIn mathematics, Computable functions are a fundamental concept within computer science and mathematics. The λ-calculus provides a simple semantics for computation, enabling properties of computation to be studied formally.Computable functions are used to discuss computability without referring to any concrete model of computation.

One first simplification is that the λ-calculus treats functions "anonymously", without giving them explicit names.For example, the function sqsum(x,y) = x*x + y*ycan be rewritten in anonymous form as (x,y) -> x*x +y*y;Similarly, id(x) = x can be rewritten in anonymous form as x -> xThe second simplification is that the λ-calculus only uses functions of a single input. An ordinary function that requires two inputs, for instance the function, can be reworked into an equivalent function that accepts a single input, and as output returns another function, that in turn accepts a single input. For example sqsum(x,y) = x*x + y*ycan be reworked into x -> (y->x*x + y*y)The lambda calculus consists of a language of lambda terms, which is defined by a certain formal syntax, and a set of transformation rules, which allow manipulation of the lambda terms.As described above, all functions in the lambda calculus are anonymous functions, having no names. They only accept one input variable, with currying used to implement functions with several variables.These are motivation behind using Lambda in Java 8 for anonymous inner classes.Lambdaexpressions address the bulkiness of anonymous inner classes by converting lines of code into a single statement. This simple horizontal solution solves the "vertical problem" presented by inner classes.Lambda Syntax in javaA lambda expression is composed of three parts.

Argument List

Arrow Token

Body

(int x, int y)

->

x + y

The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.Example:(int a, int y) -> x*x + y*y : sum of square of x and y(String str) -> { System.out.println("Welcome to Lambda Expression " + str); }Type of Lambda expressionAs functional interfaces are leveraged for use with lambda expressions. So basically is an instance of functional interface. As you see, lambda expression itself does not contain any information about which functional interface is implementing that information can been seen from the context in which we use lambda expression.For instance,(x,y) -> x*x + y*ycan be instance of the functional interfaceinterface sqsum{ int sumsquare(int a, int b);}

So you can write,

sqsum sm = (x,y) -> x*x + y*yThe data type that these methods expect is called the target type and can be compatible with different functional interfaces, so it use the same lambda expression. To determine the type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found. It follows that you can only use lambda expressions in situations in which the Java compiler can determine a target type.

ExamplesNow it's time for example, these example are executed on Java(TM) SE Runtime Environment (build 1.8.0-b128) Example 1 : Math operationIn this example, we take one interface with one abstract method that we call functional interface now.

Output :Sub lambda : 8Add lambda :6Multiply lambda :116Example 2 : Runnable interfaceI hope you know that runnable interface is functional interface, so we use this in Lambda expression and we how it reduce the code from 5 lines to 1 line.

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.