Java 8 Lambda Expressions Introduction Example
Hello readers! In this tutorial, we feature a comprehensive article on Java 8 Lambda Expressions.
1. Introduction
To achieve the benefits of functional programming in Java, JDK developers introduced Lambda Expressions in Java 8 programming.
- A lambda expression is a nameless function which does not have the name, return type, and access modifiers
- A lambda expression instance can be assigned to any interface that has only one abstract method (a.k.a Functional Interfaces)
- A lambda expression is also referred to as anonymous functions or closures
- A lambda expression in the permanent memory of JVM (i.e. Method area)
- Syntax:1
(Parameter-list) -> { Body }
1.1 Understanding Lambda Expression
- A lambda expression can never be instantiated and extend abstract or concrete classes
- A lambda expression can never have instance variables. Any variable declared inside a lambda expression is a local variable
this
keyword inside a lambda expression represents outer class object reference (i.e. the class in which the lambda expression is declared)- Functional Interfaces are required to call a lambda expression
- A lambda expression can have zero or more parameter(s)
- Programmers may or may not specify the data type of parameter(s) in a lambda expression. If the compiler detects the parameter(s) type based on the context then programmers can remove the data type. For example,12345
// Lambda expression.
(
int
a,
int
b) -> System.out.println(
"a= "
+ a +
", b= "
+ b);
// Re-written lambda expression.
(a, b) -> System.out.println(
"a= "
+ a +
", b= "
+ b);
- Multiple parameters in a lambda expression should be separated with a comma
- If the number of parameters in a lambda expression is zero, then programmers have to specify empty parameters like
()
. For example,12// Lambda expression.
() -> System.out.println(
"Hello World!"
);
- If a single parameter is available in a lambda expression and the compiler is able to detect the data type, the programmers can remove the type and parenthesis. For example,12345
// Lambda expression.
(
int
x) -> System.out.println(x);
// Re-written lambda expression.
x -> System.out.println(x);
- Similar to the method body, the lambda expression body can have multiple statements. If more than one statement is present then curly braces are mandatory, otherwise, they are optional
1.2 Advantages of Lambda Expression
- Reduces code length for increasing the code readability
- Resolves Anonymous Inner classes complexities
- Can be passed as method arguments
To start with this tutorial, we are hoping that users at present have their preferred IDE and JDK 1.8 installed on their machines. For easy usage, I am using Eclipse IDE.
2. Java 8 Lambda Expressions Introduction Example
Firstly, let us review the project structure that has a single class to demonstrate a lambda expression in Java 8.
2.1 Project Creation
This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created.
3. Application Building
To create a new class, right click on the src/main/java
folder, New -> Class
. Fill in the details about the package and class name as shown in Fig. 6 and click finish.
3.1 Lambda Expression in Play
Let us add some code to the Lambdaexpression.java
class.
Lambdaexpression.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | package jcg.lambdaexpression; @FunctionalInterface interface Interface1 { public void greetings(); } @FunctionalInterface interface Interface2 { public void name(String name); } @FunctionalInterface interface Interface3 { public void add( int a, int b); } @FunctionalInterface interface Interface4 { public int multiple( int x); } public class Lambdaexpression { public static void main(String[] args) { // Lambda expression with no parameter. Interface1 interf1 = () -> { System.out.println( "Hello World!" ); }; interf1.greetings(); // Lambda expression with single parameter. // Here java compiler can detect the parameter type based on the context (i.e. Type coherence). // Thus the lambda expression can be rewritten as :: Interface2 interf2 = (name) -> { System.out.println("My name is= " + name); }; Interface2 interf2 = (String name) -> { System.out.println( "My name is= " + name); }; interf2.name( "Java" ); // Lambda expression with multiple parameters. Interface3 interf3 = ( int a, int b) -> { System.out.println( "Total sum is= " + (a+b)); }; interf3.add( 5 , 5 ); // Lambda expression with return keyword. // Here as curly parentheses consists of a single statement, we can omit them and the return keyword. // Thus the lambda expression can be rewritten as :: Interface4 interf4 = (int x) -> x*x; Interface4 interf4 = ( int x) -> { return x*x; }; System.out.println( "Total result is= " + interf4.multiple( 10 )); } } |
4. Run the Application
Right click on the Lambdaexpression.java
class, Run As -> Java Application
. The class will be executed and the output will be printed in the ide console.
Output
1 2 3 4 | Hello World! My name is= Java Total sum is= 10 Total result is= 100 |
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
5. Conclusion
In this tutorial, we had an in-depth look at the Lambda Expressions in Java 8. Developers can download the sample application as an Eclipse project in the Downloads section.
6. Download the Eclipse Project
This was an example of Lambda Expressions in Java 8.
You can download the full source code of this example here: Java 8 Lambda Expressions Introduction Example