×

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

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

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,...

4 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.