[Java 8 Tutorial] Lambda Expressions and Functional Interfaces

Lambda Expressions and Functional Interfaces tutorial bring you to functional programming concepts in Java 8 change. Lambda Expressions and Functional Interfaces are coherent relation each other and it is reason why i put both of them into the post.

Lambda Expressions are the biggest and most waited language change in the whole Java 8 release. Lambda expressions are Java’s first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class.

Lambda Expressions and Functional Interfaces

Lambda Expressions and Functional Interfaces
A lambda expression can be passed around as if it was an object and executed on demand. They allow us to treat functionality as a method argument, or treat a code as data. In its simplest form, a lambda could be represented as a comma-separated list of parameters, the –> symbol and the body. For example:

Notice that the type of argument o is being inferred by the Java 8 compiler. Alternatively, we may explicitly declare the type of the parameter, wrapping the definition in brackets. The above code is modified like below:

In case lambda’s body is more complex, it may be wrapped into square brackets, as the usual function definition in Java. For example:

Lambdas may reference the class members and local variables. Those two snippets are equivalent:

And:

Lambda may return a value. The type of the return value will be inferred by compiler. The return statement is not required if the lambda body is just a one-liner. The two code snippets below are equivalent:

And:

Functional Interfaces

What is a Functional Interface? Simply, a function interface is an interface with just one single method. If you add just one other method to the interface definition, it happens compilation error because it will not be function anymore. To resolve this issue, Java 8 adds annotation @FunctionalInterface (and all existing interfaces in Java library have been annotated with @FunctionalInterface as well). Here is simple functional interface definition:

.And the above functional interface may be implicitly converted to a lambda expression. Notice that, The java.lang.Runnable and java.util.concurrent.Callable are two great examples of functional interfaces too.

One more thing, You can declare default and static methods in the functional interface. They don’t break the functional interface contract and may be declared like below:

That’s it.

Leave a Comment

*

Please share it if you found this useful
Hide Buttons