Java8 - Lambda Expressions Guide & examples
In this blog post, I will cover the basics of java8 Lambda expressions tutorials with examples.
Lambda Expressions java8
Lambda expressions are an important feature introduced in java8 to achieve functional programming.
This expression enables the creation of an anonyms class with the implementation of functional interfaces. Anonyms class has no name for it.
The functional interface contains only single abstract methods, introduced in java8 to achieve functional programming in java language.
Please see my previous articles on Functional Interfaces. Another way is to represent functional programming with methods of a class using method reference. Please see my previous post about Method reference.
How to write Lambda Expression in Java7?
Before java8, without lambda expression, We are going to create an anonyms class for interface implementation.
public class AnonymousClassesExample {
public static void main(String[] args) {
MathOperation mo = new MathOperation() {
@Override
public int add(int a, int b) {
return (a + b);
}
};
System.out.println(mo.add(1, 3));
}
}
interface MathOperation {
public int add(int a, int b);
}
output:
4
Java8 Lambda Expression Example
The same functionality is rewritten with a lambda expression. The amount of Code is reduced and simplified.
public class LamdaExpressionExample {
public static void main(String[] args) {
MathOperation math=(a,b)->(a + b);
System.out.println(math.add(1, 3));
}
}
@FunctionalInterface
interface MathOperation {
public int add(int a, int b);
}
Output:
4
What is the syntax of lambda?
Lambda Expression
can be created using the following syntax.
It uses an arrow operator
which contains hyphen
followed by greater
than a symbol.
The left side of the arrow operator
contains parameters
. The right side of the arrow operator have expression
or statements
(Parameters) --> expression or
(Parameters) --> {statements;}
Parameters
: These all or empty or nonempty values of the left side arrow operator. expression
: if expression specified, the semicolon
is not required and curly braces
optional Statements. if there is more than one statement, must be enclosed in curly braces
, and need to add a semicolon at end of the statement. This contains expressions/body of the lambda expression.
How to write lambda expression with Zero Parameter?
Lambda expressions can be written with empty braces followed by an arrow symbol and a single statement. Statement not required and return statement.
() -> System.out.println("Lambda Expression without Arguments");
How to write lambda expression with One Parameter?
It is an example of writing a single parameter in lambda expressions
(value) --> System.out.println("Lambda Expression with one Arguments"+value);
How to write lambda expression with multiple Parameter? It is an example of multiple parameters within lambda expressions
(value1, value2) --> System.out.println("Lambda Expression with one Arguments"+value1+value2);
Lambda expression Features
- These are functions without a name - Anonyms functions
- The body contains zero or more statements. If it is a single statement, curly braces are not required. if more than one statement, These should be enclosed in curly braces.
- Return keyword is not required by default.
- The return type of anonymous function is the same as the value type of the statements.
- These are mapped to Functional Interfaces.
Lambda expression Advantages
- Allows Functional Programming via the Functional interface.
- The reduced line of code.
- It combines with streams API is more efficient during a parallel iteration of data structures
Lambda expression Disadvantages
- It is hard to debug when an error occurs
- Difficulty to understand the code easily.
Lambda Expression Examples
The below section contains frequently used lambda expression usage examples. Lambda Expression without arguments Example This Expression can be defined without arguments. The functional interface has only one abstract method.
@FunctionalInterface
annotations are optional and not required.
public class LamdaExpressionWithoutParametersExample {
public static void main(String[] args) {
Message msg = () -> {
return "Hi How are you?";
};
System.out.println(msg.getMessage());
}
}
@FunctionalInterface
interface Message {
public String getMessage();
}
Output:
Hi, How are you?
Lambda Expression Single Argument Example Here the single argument is defined. arguments can be either enclosed in parenthesis.
public class LamdaExpressionWithParametersExample {
public static void main(String[] args) {
// Lamda expression single argument enclosed in braces
MathOperation math = (value) -> {
return value + 1;
};
// Lamda expression single argument without braces
MathOperation math1 = value -> {
return value + 1;
};
System.out.println(math.incrementByOne(1));
System.out.println(math1.incrementByOne(4));
}
}
interface MathOperation {
public Integer incrementByOne(Integer i);
}
Output:
2
5
Lambda Expression Two Arguments Example
This example contains the usage of various use cases
- Lambda Expression is defined with two arguments, argument type is not declared in this, the type is inferred from the value of the argument.
- Lambda Expression is defined with two arguments their type included.
- Lambda Expression is defined without the return keyword. When the return keyword is not defined, Curly braces are not required.
public class LamdaExpressionWithParametersExample {
public static void main(String[] args) {
// Lamda expression two argument without type of argument
MathOperation math = (v1, v2) -> {
return v1 + v2;
};
// Lamda expression two arguments with type of argument
MathOperation math1 = (Integer v1, Integer v2) -> {
return v1 + v2;
};
// Lamda expression two arguments without return type
MathOperation math2 = (Integer v1, Integer v2) -> (v1 + v2);
System.out.println(math.add(11, 6));
System.out.println(math1.add(45, 3));
System.out.println(math2.add(45, 31));
}
}
interface MathOperation {
public Integer add(Integer v1, Integer v2);
}
Output:
17
48
76
Iterate Array list with For Each Example using lambda expression
It is an example offorEach
of list objects or primitive types.
Lambda expressions are used with a single parameter that contains an iterated object of an ArrayList.
import java.util.ArrayList;
import java.util.List;
public class LamdaExpressionWithParametersExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add(1);
list.add(6);
list.add(8);
list.forEach((value) -> System.out.println(value));
}
}
Output:
1
6
8
Conclusion
In this post, Learned complete tutorials on lambda expression in java8 with examples.