×

How to use Lambda Expression in Java?

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

Interface that is Useful

Functional interface implementation is provided by the lambda expression. A functional interface is one that only contains one abstract method. An interface can be designated as a functional interface

using Java's annotation @FunctionalInterface.

How are Java Lambda Expressions implemented?

Each expression contains a secret working pattern, and the lambda expression is no different. This working pattern is shown as follows:

(intarg_a, String arg_b)
{System.out.println("two arguments"+ arg_a+" and "+arg_b);}

These two parameters, int arg a and String arg b, together with any other arguments (i.e., more than two arguments), make up the list of arguments. The lambda expression's body receives these arguments as part of an argument list thanks to the arrow token. The argument list for this arrow token constantly follows its lambda body.

The implementation of lambda expression throughout this format also takes the use of a reference implementation. However, if there are several parameter lists, the brackets or block of code must be closed, and the return statement of the anonymous procedure will then be the same as type of value that must return the block's code or void if it is not returned.

Use of Lambda Expressions

By specifying an anonymous function that may be used as a parameter to a method, a lambda expression may implement a functional interface.

  • Enables functional programming: Prior to the invention of lambda expressions, programmers were compelled to use Object-Oriented Programming (OOPS), which does not take control of the functional paradigm. As a result, lambda expressions let us create functional code.
  • Code that is clear and readable: People have begun utilizing lambda expressions and have found that doing so can significantly reduce the number of lines in their code.
  • Easy-to-Use Libraries and APIs: Lambda expressions-based APIs may be simpler to utilize and support other APIs.
  • Supports parallel processing: Because today's processors are all multi-core, a lambda expression may also help us create parallel processing.

Syntax of Java Lambda Expression

(argument-list) -> {body}  

The three elements that make up a Java lambda expression.

  1. Argument list: It may or may not be empty.
  2. Arrow token: The arrow token is used to connect the parameters list with the expression body.
  3. Body: It includes statements and lambda expression expressions.

 Syntax with no parameter

() ->
{  
//Body of a lambda with no parameters 
}   

Syntax with one Parameter

(a) ->
{  
//Body of a lambda with single parameters 
}  

Syntax with Two Parameter

(a,b) ->
{  
//Body of a lambda with multiple parameters 
}

Example Program

import javax.swing.*;
@FunctionalInterface
interface Action {
   void run(String s);
}
public class LambdaExpression {
   public void action(Action action) {
action.run("Welcome to javatPoint");
   }
   public static void main(String[] args) {
      new LambdaExpression().action((String s) ->System.out.print("*" + s + "*"));
   }
}

Output

*Welcome to javatPoint*

Example of a zero parameter

interface Say{
    public String say();  
}  
public class LambdaExpression{
public static void main(String[] args) {  
    Say s=()->{  
        return "Empty";  
    };  
System.out.println(s.say());  
}  
}

Output

Empty

Example of a single parameter

interface Say{
    public String say(String name);  
}  
public class LambdaExpression{
    public static void main(String[] args) 
{  
        Say s1=(name)->
{  
            return "Hi, "+name;  
        };  
System.out.println(s1.say("chintu"));  
        Say s2= name ->
{  
            return "Hi, "+name;  
        };  
System.out.println(s2.say("chintu"));  
    }  
}  

Output

Hi, chintu
Hi, chintu

Example of a multiple parameters

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

Output

40
1000

Benefits of the Lambda Expression

  • 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

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

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

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.