New in Java 8 : Lambda Expressions

Java 8 was released last march 2014. This release has new features, that will help you as java developer to improve your code. The main features  of JDK8 are the Lambda Expressions, Nashorn Javascript engine and new APIs for Strings, Streams, Date and Time.

Lambda expressions make instances of anonymous classes easier to read and write. A lambda expression represents a shorthand notation for implementing the functional interface.

A functional interface is a new type of interface that java 8 introduces, it’s also called SAM-Interface (Single Abstraction Method Interface). It represents an interface with only one abstract method.  Example for SAM-Interfaces are Runnable, Callable  or Comparator<T> interfaces.  From this point forward, i’ll refer to lambda expressions simply as lambdas.

Here is a concrete example:

In Java 7:

In Java 8:

A lambda consists of a parameter list followed by the arrow token (->) and a body :

As you can see in the example, lambdas make the code flexible and better readable.

You can optionally use the new annotation @FunctionalInterface  to mark an interface for which lambdas can be used.

Since java already knows the expected parameter types for the single method of  the functional interface , you don’t need to write them.

You can also omit the return in the lambda when the method has just one statement:

Java 8 introduces a new package java.util.function that contains a large number of prebuild interfaces for which lambda can be used ( DoubleUnaryOperator, IntUnaryOperator, DoubleConsumer, LongConsumer … ).  If you want to create a new SAM-Interface look first of all through this new package and see if one of the SAM-Interfaces there can be used instead.

To learn more about lambdas i recommand reading the book Java 8 Lambdas by Richard Warburton.

Happy coding.

Leave a Reply

Next ArticleAutomated WPF Testing with Telerik Test Studio