What is a Lambda Expression in Java 8 - onlyxcodes

Wednesday, 27 April 2022

What is a Lambda Expression in Java 8

You will learn about lambda expressions in Java 8 in this post.


It's a new Java 8 feature. The Lambda expression is used to provide a functional interface implementation. It helps you save a lot of code.


We do not declare the method again during the lambda expression program to supply the implementation. We simply write the implementation code here.


This post covers the following topics in addition to the Java Lambda Expression concept:


Implement Lambda Expression in Java. 


Why use Lambda Expression. 


What is the Functional Interface? 


Return Type of Lambda Expression in Java.


Lambda Expression Real Time example.


Advantages of Lambda Expression.


Interview questions of Lambda Expression and also MCQ questions.


lambda expressions java 8 - advantages of lambda expressions in java - interview questions of java lambda expressions - return type of lambda expressions in java 8


Table Content

1. What is Lambda Expression in Java?

2. Why use Lambda Expression

3. What is return type of Lambda Expression in Java 8?

4. Advantages of Lambda Expressions in Java

5. Best Practices for Java Lambda Expressions

6. Interview Questions of Lambda Expression In Java

7. Java Lambda Expression MCQ


1. What is Lambda Expression in Java?

The new feature of Java 8 is Lambda Expression. It's a function. To put it in other words, the function has no name, return type, or access modifiers (private, public, or protected). Anonymous functions are also known as lambda expressions.


Lambda expressions are available in other programming languages such as Python, Ruby, C#, and others.


Lambda Expressions has the following functionalities.


In Java, lambda expressions allow us to treat functionality as a method parameter or code as data.


The Lambda expression is used to provide a functional interface implementation.


A function that can be written independently of any class.


It allows you to iterate over a collection, filter it, and retrieve data.


Syntax:


(parameter list) -> { expression body }

The Lambda expression is made up of three parts.


  • The first part is an argument list, which might have zero, one, or several arguments and is wrapped by parenthesis.

  • The second part is the Arrow-Token (->), which connects the list of arguments to the expression body.

  • The method body, which contains expressions and statements for lambda expressions, is the third part.

Before Java 8, there was a strategy.


Developers used to utilize Anonymous class syntax to convey functionality to other methods or constructors before lambda expressions were developed.


Let's look at an example where the Java lambda expression isn't used.


We have a single abstract method in this interface, and we're implementing it without using the lambda expression.


The Train interface is implemented in Java using an anonymous class.


interface Train
{  
    public void kilometer();  
}  
public class Test 
{  
    public static void main(String args[]) 
	{  
        int speed = 100;  
  
        //without lambda expression, Train implementation using anonymous class  
        Train t = new Train()
		{  
            public void kilometer()
			{
				System.out.println("Speed "+ speed);
			}  
        };  
		
        t.kilometer();  
    }  
}

Output:


Speed 100

Strategy Following the Implementation of Lambda Expressions in Java 8


Now we put the Java lambda expression into the program.


The lambda expression in the above example is implemented in the Java program below.


{  
    public void kilometer();  
}  
  
public class Test
{  
    public static void main(String args[]) 
	{  
        int speed = 100;  
          
        //with lambda expression implementation 
        Train t=()->{  
            System.out.println("Speed "+speed);  
        };  
		
        t.kilometer();  
    }  
}

Output:


Speed 100

Program: Lambda Expression No Parameter


Using the lambda expression, we write a Java program that returns the simple hello world string.


interface Hello
{  
    public String display();  //a method with no parameter
}  
public class Test
{  
	public static void main(String args[]) 
	{  
		Hello h = () -> {  
			return "hello world";  
		};  
	
		System.out.println(h.display());  
	}  
}

Output:


hello world

Explanation:


In the example below, we've created a Hello interface. It only has one abstract method named display(), which does not take any parameters.


interface Hello
{  
    public String display();  //a method with no parameter
}

We've generated a reference of the Hello interface within the Main class.


Finally, we use the reference interface to execute the function display() within the System.out.println() statement.


Hello h = () -> {  
	return "hello world";  
};  
	
System.out.println(h.display());

Program: Lambda Expression With Single Parameter


Methods can be used to create lambda expressions with zero, one, or multiple parameters.


This Java program shows how to use a lambda expression with functional parameters, sending a single parameter from the interface function and the lambda expression that goes with it.


interface Train
{  
    public int kilometer(int speed);  //a method with single parameter
}  
public class Test
{  
	public static void main(String args[]) 
	{  
		// lambda expression with single parameter trainSpeed and without type declaration
		
		Train t = (trainSpeed) ->  trainSpeed + 50; 
	
		System.out.println("train one hour kilometer speed is " +t.kilometer(50));  
		
		
		// lambda expression with single parameter trainSpeed and with int type declaration
		
		Train t1 = (int trainSpeed) ->  trainSpeed + 100; 
	
		System.out.println("train two hour kilometer speed is " +t1.kilometer(100));  
		 
	}  
} 

Output:


train one hour kilometer speed is 100
train two hour kilometer speed is 200

Explanation:


In the example below, we've created a Train interface. It includes a method named kilometer(), which takes only one parameter.


interface Train
{  
    public int kilometer(int speed);  //a method with single parameter
}

Two references (t and t1) have been made within the Main class. 


Look at the left side of the arrow operator, where we supply a single parameter (trainSpeed) that the lambda expression accepts.


Look to the right of the arrow operator, where the parameter is specified and the 50 value is added. The body of the lambda expression is specified using the right side of the arrow operator.


The body of the lambda expression is specified using the right side of the arrow operator.


We use the "t" reference to call the function kilometer() and display the added value inside the System.out.println() statement.


// lambda expression with single parameter trainSpeed and without type declaration

Train t = (trainSpeed) ->  trainSpeed + 50; 
	
System.out.println("train one hour kilometer speed is " +t.kilometer(50));  

In the second instance, we used the same strategy as before.


The difference is that we used the type of the parameter we specified. And then use the second reference, t1, to invoke the method.


On the left side of the arrow operator, we specify a single int type parameter (trainSpeed) that the lambda expression accepts.


We define the parameter and add the number 100 to the right of the arrow operator. We use the "t1" reference to call the method kilometer() and display the added value inside the System.out.println() statement.


// lambda expression with single parameter trainSpeed and with int type declaration
		
Train t1 = (int trainSpeed) ->  trainSpeed + 100; 
	
System.out.println("train two hour kilometer speed is " +t1.kilometer(100));

Program: Lambda Expression With Multiple Parameters


We know that the Lambda Expression can contain multiple parameters, therefore we can use methods to achieve that.


This Java program demonstrates the Multiple parameter lambda Expression with the Addition functional interface and values to be added using the add() method of the interface.


interface Addition
{  
    public int add(int i, int j);  //a method with two parameters
}  
public class Test
{  
	public static void main(String args[]) 
	{  
		// lambda expression with two parameters p and q and without type declaration
		
		Addition a = (p, q) ->  p + q; 
	
		System.out.println("addition is " +a.add(50,50));  
		
		
		// lambda expression with two parameters p and q and with int type declaration
		
		Addition a1 = (int p, int q) ->  p + q; 
	
		System.out.println("addition is " +a1.add(100,100));
		 
	}  
}

Output:


addition is 100
addition is 200

Explanation:


We've constructed a functional interface called Addition in the example below. It includes a method called add(), which takes two parameters.


interface Addition
{  
    public int add(int i, int j);  //a method with two parameters
}

We have two references to Addition in the Main class, which are a and a1.


In the round bracket without type on the left side of the arrow operator, we specify the two parameters p and q, which the lambda expression accepts.


For the addition operation, we added p and q arguments to the right of the arrow operator. We call the method add() using the "a" reference and pass the parameters 50 and 50 inside the System.out.println() statement.


// lambda expression with two parameters p and q and without type declaration
		
Addition a = (p, q) ->  p + q; 
	
System.out.println("addition is " +a.add(50,50));

In the second instance, we used the same strategy as before.


The difference is that we used the type of parameters we specified. And use the second reference to invoke the method, which is a1.


The two arguments p and q are specified on the left side of the arrow operator in the round bracket of int type, which the lambda expression accepts.


For the addition operation, we added p and q arguments to the right of the arrow operator. We execute the method add() using the "a1" reference and pass the parameters 100 and 100 inside the System.out.println() statement.


We execute the method add() using the "a1" reference and pass the parameters 100 and 100 inside the System.out.println() statement.


// lambda expression with two parameters p and q and with int type declaration
		
Addition a1 = (int p, int q) ->  p + q; 
	
System.out.println("addition is " +a1.add(100,100));

Program: Lambda Expression using return Statement


With a lambda expression, the return statement is optional. We can use it to give the method a value.


We utilized two lambda expressions in this example, the first of which does not employ the return statement and the second of which does.


interface Addition
{  
    public int add(int i, int j);  //a method with two parameters
}  
public class Test
{  
	public static void main(String args[]) 
	{  
		// lambda expression with two parameters p and q and without return keyword and type 
		
		Addition a = (p, q) ->  p + q; 
	
		System.out.println("addition is " +a.add(20,20));  
		
		
		// lambda expression with two parameters p and q and with return keyword and int type
		
		Addition a1 = (int p, int q) ->  {
			return p + q; 
		};
		
		System.out.println("addition is " +a1.add(40,40));
		 
	}  
}

Output:


addition is 40
addition is 80

Explanation:


We've established a functional interface called Addition in the example below. It includes a method named add(), which takes two parameters.


interface Addition
{  
    public int add(int i, int j);  //a method with two parameters
}

We have two references to Addition in the Main class, which are a and a1.


In the round bracket without type on the left side of the arrow operator, we specify the two parameters p and q, which the lambda expression accepts.


Look to the right of the arrow operator for more information. For the addition operation, we used the p and q arguments instead of the return keyword and curly braces. We call the method add() using the "a" reference and pass the parameters 20 and 20 inside the System.out.println() statement.


We call the method add() using the "a" reference and pass the parameters 20 and 20 inside the System.out.println() statement.


// lambda expression with two parameters p and q and without return keyword and type 
		
Addition a = (p, q) ->  p + q; 
	
System.out.println("addition is " +a.add(20,20));  

In the second instance, we used the same tactics as before. The only difference is that we utilized the return keyword and curly brackets.


The two arguments p and q are specified on the left side of the arrow operator in the round bracket of int type, which the lambda expression accepts.


For the addition operation, we added p and q arguments to the right of the arrow operator. We've utilized curly brackets and the return keyword.


We execute the method add() using the "a1" reference and pass the parameters 40 and 40 inside the System.out.println() statement.


// lambda expression with two parameters p and q and with return keyword and int type
		
Addition a1 = (int p, int q) ->  {
	return p + q; 
};
		
System.out.println("addition is " +a1.add(40,40));

Program: Lambda Expression in Foreach Loop 


To implement a functional interface, we can utilize lambda expressions everywhere.


To iterate the collection components, the Java program below implements a lambda expression. The iterator interface's forEach() strategy was applied here.


import java.util.ArrayList;
import java.util.List;

public class Test 
{  
    public static void main(String args[]) 
	{    
  
    	List<String> colors = new ArrayList<>();
    	colors.add("red");
    	colors.add("blue");
    	colors.add("yellow");
    	colors.add("green");
		
    	// walk using foreach
    	System.out.println("Walk using foreach");
    	for(String element: colors) 
		{
    		System.out.println(element);
    	}
		
    	// walk using lambda expression
    	System.out.println("Walk using lambda expression");
    	colors.forEach(element->System.out.println(element));
    }  
}

Output:


Walk using foreach
red
blue
yellow
green
Walk using lambda expression
red
blue
yellow
green

Program: Create Thread By Lambda Expression


The Runnable interface in Java is a functional interface with only one abstract method. We may use the lambda expression to implement its run() method and generate the thread object, as shown below.


In this java program, I applied for loop to print 1 to 3 numbers in both two threads created. 


public class Test 
{
	public static void main(String args[]) 
	{
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				System.out.println("Thread is running without lambda expression");
				for (int i = 1; i <= 3; i++) {
					System.out.println(i);
				}
			}
		});
		
		t1.start();
		
		Thread t2 = new Thread(() -> {
			System.out.println("Thread is running with lambda expression");
			for (int j = 1; j <= 3; j++) {
				System.out.println(j);
			}
		});
		
		t2.start();
	}
}

Output:


Thread is running without lambda expression
1
2
3
Thread is running with lambda expression
1
2
3

2. Why use Lambda Expression

Implements functional Interface: The implementation of a functional interface is important.


Decrease lots of Code: We have already shown how easy we can generate objects of a functional interface using lambda expression rather than an anonymous class, which is one of the clear advantages of integrating lambda expression.


What is the Functional Interface?


A functional interface is defined as an interface that has only one abstract method and is specified with the @FunctionalInterface annotation.


Because of the Single Abstract Method (SAM), a functional interface is also known as the SAM interface.


Runnable, Callable, and Comparable are some examples. Because they all have a single abstract method, these are the functional interfaces.


Functional Interface Example


We made a functional interface with only one abstract method that's annotated with the @FunctionalInterface annotation.


@FunctionalInterface
interface Message
{  
    public void show();  
}

Implements Functional Interface by Lamda Expression


A lambda expression is used to implement a functional interface in this example. The lambda expression is used to implement an abstract method show() inside the Test class.


@FunctionalInterface
interface Message
{
	public void show();
}

public class Test 
{
	public static void main(String args[]) 
	{
		// Implementing functional interface using lambda expression
		Message m = () -> System.out.println("hello world");
		m.show();
	}
}

Output:


hello world

3. What is return type of Lambda Expression in Java 8?

Lambda expressions, as you may know, implemented the Functional interface. It establishes a connection to the interface and delivers the abstract method to the body. With a lambda expression, we've seen a lot of examples.


We'll now look into how Lambda expressions interact with return statements. Let's assume that any Functional interface has an abstract method. The return type is given for the abstract method.


public int display(int i);

As a result, we must consider the method's return type while passing it to the body. A return statement can be used to return the value.


We have two options for returning the value. As a result, we'll look at two instances.


1. Without return statement


2. With return statement


1. Without a return statement


If there is only one line of code in a Lambda expression and no curly brackets {} are used. You don't have to return the statement in this case. All you have to do now is write the variable you want to return.


interface Demo 
{
    public int display(int i);
}

public class Test
{
    public static void main(String args[]) 
    {
        Demo d = (int a) ->  a;      
        System.out.println("value return by lambda expression = "+d.display(10));
    }
}

Output:


value return by lambda expression = 10

2. With return statement


If your Lambda expression has more than one line of code and you're applying curly brackets {}. The statement must then be returned. You must write the variable that you want to return with the return statement.


Because we're applying curly braces in this example, we'll need to include return statements.


interface Demo 
{
    public int display(int i);
}

public class Test
{
    public static void main(String args[]) 
    {
        Demo d = (int a) -> { 
			return a; 
		};    
		
        System.out.println("value return by lambda expression = "+d.display(20));
    }
}

Output:


value return by lambda expression = 20

Example of the lambda expression with a real time example.


Program without return statement


package mypackage;

import java.util.List;

public interface Display 
{
	public List<Employee> show();

}

package mypackage;

public class Employee 
{
	int id;
	String skill;
	String name;
	
	public Employee(int id, String skill, String name) {
		super();
		this.id = id;
		this.skill = skill;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getSkill() {
		return skill;
	}

	public void setSkill(String skill) {
		this.skill = skill;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}	

package mypackage;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test 
{
	public static void main(String args[])
	{
		ArrayList<Employee> listOfEmployee = new ArrayList<>();
		
		listOfEmployee.add(new Employee(5, "Web Developing", "Hamid"));
		listOfEmployee.add(new Employee(9, "Database Design", "Ankit"));
		listOfEmployee.add(new Employee(11, "Java Programming", "Faisal"));
		
		//without return 
		Display d = () -> listOfEmployee.stream().filter(employee -> 
		employee.getId() < 9).collect(Collectors.toList());
		
		List<Employee> list = d.show();
		list.forEach(emp -> System.out.println("Name of Employee: " +emp.getName()));
	}

}

Output:


Name of Employee: Hamid

Program with the return statement


package mypackage;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test 
{
	public static void main(String args[])
	{
		ArrayList<Employee> listOfEmployee = new ArrayList<>();
		
		listOfEmployee.add(new Employee(5, "Web Developing", "Hamid"));
		listOfEmployee.add(new Employee(9, "Database Design", "Ankit"));
		listOfEmployee.add(new Employee(11, "Java Programming", "Faisal"));
		
		// with return
		Display d = () -> {
            return listOfEmployee.stream()
            .filter(employee -> employee.getId() < 9)
            .collect(Collectors.toList());    
        };
		
		List<Employee> list = d.show();
		list.forEach(emp -> System.out.println("Name of Employee: " +emp.getName()));
	}

}

Output:


Name of Employee: Hamid

4. Advantages of Lambda Expressions in Java

A lambda expression can have one or more statements in its body.


If there is only one statement, curly brackets are not required.


Use the return statement only if the method description specifies a return type.


A lambda expression can have zero, one, or more parameters.


The type of parameter might be stated directly or inferred from the specific instance.


When there is only one parameter, parentheses are not required. The use of parentheses is optional.


5. Best Practices for Java Lambda Expressions

When working with lambda expressions in Java, you should follow the following guidelines:


  • Using standard functional interfaces is a great thing.

  • Your lambda expressions should be as brief as possible.

  • In functional interfaces, avoid using so many default methods.

  • Parameter types should not be specified.

  • To create functional interfaces, use lambda expressions.

  • Overloading methods with functional interfaces as parameters is not recommended.

6. Interview Questions of Lambda Expression In Java

1. What is the lambda expression in Java?


Answer: Lambda expressions are functions that don't have a name or a set of identifiers. It is an anonymous method in and of itself. It facilitates a functional interface with just abstract methods implemented.


For example, to offer an implementation of a method described by a functional interface, a method with no name is applied.


2. What is a functional interface?


Answer: An interface with only one abstract method is called a functional interface. A functional interface is often known as a SAM type, where SAM stands for Single Abstract Method.


The Runnable interface, which contains only one method run(), is an example of a functional interface in Java.


public interface Runnable {
  public void run(); 
}

3. How many parameters can a lambda expression have?


Answer: There can be zero, one, or multiple parameters in a lambda expression.


//Zero parameter lambda expression
() -> System.out.println('No parameters');

//One parameter lambda expression
(a) -> a*20;

//Multiple parameter lambda expression
(a, b) -> System.out.println(a+b);

4. Explain the syntax of the Lambda expression in Java?


Answer: The structure of the lambda expression is split into three parts:


1. Parameters or Argument-list


There can be zero, one, or more parameters in a lambda expression.


() -> { System.out.println("Hello") }; //Without argument, will print hello 

(int i) -> { System.out.println(i) } //; One argument, will print value of i

(int i, int j) -> {i+j};//two argument, will return sum of these two integers

You don't have to declare the type of parameters because it can be determined from the context.


(i,j) -> {i+j}; //two argument, will return sum of these two numbers

It is not necessary to use parentheses when there is only one argument and its type can be determined.


i -> { System.out.println(i) };

2. Array token (->)


The lambda arrow operator is the name for the arrow token. Its purpose is to either divide the parameters from the body or to point the list of arguments to the body.


3. Body


Expressions or statements can be made by the body.


The curly brace is not required if the body contains only one statement, and the anonymous function's return type is the same as the body expression.


If there are many statements, they should be wrapped in curly braces, and the anonymous function's return type should be the same as the value returned from the code block, or void if nothing is returned.


5. What are the characteristics of the Lambda Expression?


Answer: The Lambda Function has the following main characteristics:


A Lambda Expression-defined method can be provided as a parameter to another method.


A method can exist without being associated with a class.


The parameter type does not need to be declared because the compiler can determine it from the parameter's value.


When using many parameters, we can use parentheses, but when using a single parameter, we don't require them.


Curly braces are not required if the body of the expression consists of a single statement.


6. Create Thread using Lambda Expression.


public class Demo
{
	public static void main(String args[])
	{
		//Create Thread with Lambda Expression 
        Runnable r = () -> {  
                System.out.println("Thread is running with lambda expression");  
        };  
		
        Thread t = new Thread(r);  
        t.start();  
    }  
}

Output:


Thread is running with lambda expression

7. Is it possible to have multiple lines of code in the body of a lambda function?


Answer: Yes, within curly brackets, the lambda function body can have many lines of code.


8. In a lambda expression, is it necessary to define the type of parameters?


Answer: With most instances, specifying the type for parameters in a lambda expression is unnecessary. The type of the parameters is determined by the java compiler by comparing them to the parameter types of the abstract method of the functional interface.


9. Is it possible to use lambda expressions to implement interfaces with default and static methods?


Answer: Only if the interface has a single abstract method can lambda expressions be used to implement interfaces with default and static methods. A functional interface is what it's called.


10. What is a SAM Interface?


Answer: The concept of a Functional Interface, which can only have one abstract method, was introduced in Java 8. These interfaces are commonly referred to as SAM Interfaces because they only specify one abstract method. "Single Abstract Method" is what SAM stands for.


7. Java Lambda Expression MCQ (Multiple Choice Questions and Answers)

1. Lambdas introduced in Java 8 allow us to treat -


a. Data as code


b. Code as data


c. none


d. all


Answer:  Code as data


2. Lambda expressions in Java 8 are based on ___


a. Procedural programming


b. Functional programming


c. Data programming


d. All


Answer:  Functional programming


3. What is the return type of the lambda expression?


a. String


b. Object


c. Function


d. void


Answer: Function


4. Which of the following are valid lambda expressions? 


a. String s1, String s2 -> System.out.print(s1+ s2);


b. () -> return;


c. (int p) -> p;


d. (int p) -> p++; return p;


Answer : (int p) -> p;


5. A lambda expression can be used...


a. As a conditional expression in an if statement


b. As a method argument


c. In a throw statement


d. In a return statement


Answer: b and d


6. Which of the following statements are true?


a. Lambda expressions don't return values


b. Curly braces are required whenever the return keyword is used in a lambda expression


c. A return keyword is always optional in a lambda expression


d. A return keyword is always required in a lambda expression


Answer:  b


7. How many methods are there in the functional interface?


a. 0


b. 1


c. 2


d. 3


Answer:  1


8. What does SAM mean in the context of the functional interface?


a. Simple Abstract Markup


b. Simple Active Markup


c. Single Abstract Method


d. Single Ambivalue Method


Answer: Single Abstract Method

No comments:

Post a Comment

Post Bottom Ad