×

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java?

In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods, lambda expressions can be used directly in a method's body and do not require a name.

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression. It is quite useful for a library's collection. It is beneficial to sort through a collection of data, iterate it over it, and extract relevant data. The use of the Lambda expression allows for the implementation of interfaces with such a functional interface. Code is saved in large amounts. A lambda expression avoids this problem by allowing the implementation to be provided without redefining the method.

Just the implementation code is written here. Java lambda expressions are considered functions; hence the compiler does not produce a .class file.

Return Type

Return statements are not considered to be expressions in lambda expressions. Statements need to be enclosed in braces ({}). A void method call need not, however, be enclosed in braces. A functional interface must be the means of the process of a method where a lambda expression is used in the return statement.

As you are aware, the Functional interface was provided by Lambda expression. It gives the body access to the abstract method and establishes a reference for the interface. A lambda expression has been used in numerous examples before.

We will now talk about how return statements interact with lambda expressions. Let's assume that any Functional interface contains an abstract method. The return type is declared together with the abstract procedure.

public int show(int a);

Therefore, we must consider the return type while passing the method to the body. You can employ a return statement to return the value.

There are two ways we can return the value. We shall thus talk about it using two examples.

1. Not including a return statement

If your lambda expression only contains one line of code and you don't use curly brackets, then. The statement need not be returned in that case. Simply write the object or variable you would like to return.

Syntax

public interface Display 
{
    public int show(int a);
}

Example program

public class ExampleWithLambda
{
    public static void main(String[] args) 
    {
        Display display = (int a) ->  a;      
System.out.println("Returns value from lambda expression = "+display.show(5));
    }
}

Output

returns value from lambda expression = 5

2. Including a return statement

If you are using curly braces () and your lambda expression contains more than one line of code. The statement must then be returned. The object or variable that you would like to return must be written with a return statement. Since we are utilizing curly braces in this example, return statements are required.

syntax

public interface Display 
{
    public int show(int a);
}

Example programs

public class ExampleWithLambda
{
    public static void main(String[] args) 
    {
        Display display = (int a) ->{ return a; };     
System.out.println("Returns value from lambda expression = "+display.show(5));
    }
}

Output

returns value from lambda expression = 5

Example 2:

public class LambdaReturnEx {
   interface Addition {
      int add(int x, int y);
   }
   public static Addition getAddition() {
      return (x, y) -> x + y; 
   }
   public static void main(String args[]) {
System.out.println("The addition is: " + getAddition().add(40, 30));
   }
}

Output

The addition is: 70

Example 3:

public class LambdaReturnEx {
   public static void main(String args[]) {
      Thread th = new Thread(getRunnable());
th.run();
   }
   public static Runnable getRunnable() {
return() -> {    
System.out.println("Lambda Expression Return Statement");
      };
   }
}

Output

Lambda Expression Return Statement

Example 4:

interface Addable{
    int add(int x,int y);  
}  
public class LambdaExpressionEx{
    public static void main(String[] args) {  
        Addable ad1=(x,y)->(x+y);  
System.out.println(ad1.add(30,10));  
        Addable ad2=(int x,int y)->{  
                            return (x+y);   
                            };  
System.out.println(ad2.add(200,600));  
    }  
}  

Output

40
800

Benefits

  • Less Code: One of the main advantages of using lambda expressions is that there are fewer lines of code to write. We are aware that only a functional interface enables the use of lambda expressions. For instance, since Framework to address is a functional language, lambda expressions are simple to use.
  • Support for parallel and sequential execution through the use of behaviour arguments in methods Java 8's Stream API is used to pass the functions to collection methods. Now, it is up to the collection to decide whether to handle the elements sequentially or concurrently.
  • More Efficiency When doing bulk operations on collections, we can obtain higher efficiency (parallel processing) by leveraging the Stream API as well as lambda expressions. Additionally, rather than using external iteration, lambda expressions make it possible to iterate collections internally.

Related Topics

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.