Java 8 – Lambda Expressions

Lambda expressions are new feature in Java 8. We now can represent one method interface by using an expression.

I. Overview
1. Pass a method as argument

Assume that we have 2 math operations: addition and subtraction. Those operations will be chosen in specific cases with 2 numbers: a and b. So the math operation is considered as an argument to method:

To make thing done, in normal approach, we declare an interface:

and two implementations:

Main function will be:

And the context to use them:

An Anonymous Inner Class is used instead of creating a implementation class for IMathOperation interface.

2. Using Lambda Expressions

We can see that it is not easy to pass a method to a function in Java, so Java 8 provides a new feature called Lambda Expressions.
Using this kind of feature, we only need to create a interface like the old interface.

All implementations of the interface and Anonymous Inner Class will be replaced by very simple expressions:

II. Lambda Expressions
1. Syntax
Argument List Arrow Token Body Note
(arg1, arg2…) -> { body }
(int a, int b) -> a + b with type declaration
(a, b) -> a + b no type declaration
(int a, int b) -> {return (a + b)} with return statement
a -> a*a*a no parenthesis
() -> 42 no arguments
(String s) -> {System.out.print(s);} returns nothing

– A lambda expression can have zero, one or more parameters.
– No need to declare type of a parameter.
– No need to write parenthesis around parameter if there is only one parameter (required if more).
– No need to use curly braces in expression body if there is only one statement (required if more).
– No need to use return keyword if there is only one statement. The compiler returns the value automatically.

2. Common use cases

Using Lambda Expressions make beautiful and lean code than using Anonymous Inner Class.
Runnable Lambda: java.lang.Runnable is an example of Functional Interface which we will learn in the next article.

Comparator Lambda:

Listener Lambda(also a Functional Interface):

III. Source code

– Java 8
– Eclipse Mars.1 Release (4.5.1)

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *