Lambda expressions are similar to methods and are a short block of code that takes in parameters and returns a value. They are added in Java 8. In this article, we will learn about lambda expressions in detail covering all the What, Why, Where, When, When Not! Just to have an idea first:
But first, let's learn about the pre-requisite before deep diving into the lambda expressions.
Functional Interface
Lambda expressions are nothing but the implementation of the functional interface. A functional interface is nothing but an interface that has only one abstract method. To declare an interface as a functional interface, Java provides an annotation @FunctionalInterface.
What are Lambda Expressions?
They are anonymous or unnamed method that does not execute on their own. They are like functions that take arguments and do some functionality and return the corresponding value. Lambda expressions don't need a name and can be implemented in the body of the method itself.
Lambda expressions are defined using the below declaration:
() -> { // Add some functionality like print some statements }
Let's take an example of how we use a lambda expression.
Consider the below method which returns us a pi value:
double getPiValue() { return 3.1415; }
Using lambda expression, we can write this method as:
() -> 3.1415
In the above example, the left side does not have any parameters, and then we have the ( -> ) arrow operator and then on the right side, we have the functionality.
Note that :
- lambda expressions are used to implement a method defined by a functional interface.
- It is the one way to represent one method interface using an expression and helps to iterate, filter, and extract data from the collection (An example is java.lang.Runnable). They are treated as a function, so the compiler does not create a .class file.
Let's take one more example :
Now we will write a program to return the value of pi, as we did above using the lambda expressions. We know that lambda expressions do not execute on their own. Instead, they form the implementation of the abstract method defined by the functional interface.
So, we have to first define a functional interface:
// Welcome to FavTutor import java.lang.FunctionalInterface; // this is functional interface @FunctionalInterface interface MyInterface{ // abstract method double getPiValue(); } public class Main { public static void main( String[] args ) { // declare a reference to MyInterface MyInterface ref; // lambda expression ref = () -> 3.1415; System.out.println("Value of Pi = " + ref.getPiValue()); } }
Output:
Value of Pi = 3.1415
In the above example,
- We first created a functional Interface named "MyInterface" which has one abstract method named "getPiValue()".
- Then in the main class, a reference to MyInterface has been declared (Note: We can declare the reference to an interface but we cannot instantiate an interface).
- Then we store the lambda expression having pi value to reference named "ref".
- Finally, we call the getPiValue() method to call the lambda expression.
Why Use Lambda Expressions?
- It can be created as a function without belonging to any class.
- To illustrates the implementation of the Functional interface.
- Reduced code length.
Advantages of Lambda Expressions
There are many advantages of using lambda expressions as given below:
-
Conciseness
-
Reduction in code bloat
-
Readability
-
Elimination of shadow variables
-
Encouragement of functional programming
-
Code reuse
-
Enhanced iterative syntax
-
Simplified variable scope
-
Less boilerplate code
-
JAR file size reductions
-
Parallel processing opportunities
Java Lambda Expression Syntax
It consists of only a parameter list and an expression. In simpler terms, it consists of the following:
- Argument-list: It can contain any number of arguments/parameters. For example 0, 1, 2, and so on...
- Arrow-token: Used to link an arguments-list and an expression.
- Body: Contains expressions and statements for lambda expression.
Note: The way functions accept parameters similarly lambda expressions accept parameters.
Now, let us look at syntax for lambda expression:
Syntax: without any parameter (No Parameter)
() -> { //Body of no parameter lambda }
Syntax: with 1 parameter
(parameter1) -> { //Body of one parameter lambda }
Syntax: with 2 parameters
(parameter1, parameter2) -> { //Body of two/multiple parameter lambda }
Java Program Without Lambda Expression
Shown below is the java program in which we are not implementing any Java lambda expression but we are implementing an interface without using a lambda expression:
// Welcome to FavTutor interface Drawable{ public void draw(); } public class LambdaExpressionExample { public static void main(String[] args) { int width=10; //without using lambda, Drawable implementation Drawable d=new Drawable(){ public void draw(){System.out.println("Drawing "+width);} }; d.draw(); } }
Output :
Drawing 10
Now, let's take a look at various examples implemented using lambda expressions given below.
Java Programs With Lambda Expression
01) foreach() method:
In the below, we have used ArrayList's foreach() method to print every item in the list:
// Welcome to FavTutor import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.forEach( (n) -> { System.out.println(n); } ); } }
Output :
10 20 30 40
02) No parameter:
// Welcome to FavTutor interface Sayable{ public String say(); } public class LambdaExpressionExample3{ public static void main(String[] args) { Sayable s=()->{ return "I have FavTutor to learn"; }; System.out.println(s.say()); } }
Output :
I have FavTutor to learn
03) One parameter:
// Welcome to FavTutor interface Sayable{ public String say(String name); } public class LambdaExpressionExample4{ public static void main(String[] args) { // single parameter. Sayable s1=(name)->{ return "Hello, "+name; }; System.out.println(s1.say("FavTutor")); //can omit parentheses Sayable s2= name ->{ return "Hello, "+name; }; System.out.println(s2.say("FavTutor")); } }
Output :
Hello, FavTutor Hello, FavTutor
04) Two parameters:
// Welcome to FavTutor interface Addable{ int add(int a,int b); } public class LambdaExpressionExample5{ public static void main(String[] args) { // Multiple parameters in lambda expression Addable ad1=(a,b)->(a+b); System.out.println(ad1.add(10,20)); // Multiple parameters with data type in lambda expression Addable ad2=(int a,int b)->(a+b); System.out.println(ad2.add(100,200)); } }
Output :
30 300
05) Creating Thread:
// Welcome to FavTutor public class LambdaExpressionExample9{ public static void main(String[] args) { //Thread Example without lambda Runnable r1=new Runnable(){ public void run(){ System.out.println("Thread1 is running..."); } }; Thread t1=new Thread(r1); t1.start(); //Thread Example with lambda Runnable r2=()->{ System.out.println("Thread2 is running..."); }; Thread t2=new Thread(r2); t2.start(); } }
Output :
Thread1 is running...
Thread2 is running...
06) Event Listener:
// Welcome to FavTutor import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; public class LambdaEventListenerExample { public static void main(String[] args) { JTextField tf=new JTextField(); tf.setBounds(50, 50,150,20); JButton b=new JButton("click"); b.setBounds(80,100,70,30); // lambda expression implementing here. b.addActionListener(e-> {tf.setText("hello swing");}); JFrame f=new JFrame(); f.add(tf);f.add(b); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(null); f.setSize(300, 200); f.setVisible(true); } }
Conclusion
Lambda expression's body can contain zero, one, or more statements. In the case of a single statement, curly brackets are not required and the return type of both the anonymous function and the body expression will be the same.
In this article, we looked at the lambda expression's definition, declaration, and syntax with multiple examples. Congratulations on getting this far! Now give yourself a pat on the back. Good job!