The Wayback Machine - https://web.archive.org/web/20240618222623/https://www.geeksforgeeks.org/java-lambda-expressions-parameters/
Open In App

Java – Lambda Expressions Parameters

Last Updated : 25 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java.lang.Runnable.

Lambda expressions implement only one abstract function and therefore implement functional interfaces. Predicate interface is an example of a functional interface that has only one abstract method called test().

Illustration:

interface Predicate
{
    ......
    abstract boolean test(T t)
}

The above is a functional interface that has one abstract method test receiving only one parameter of type T and returns a boolean value. This method is a generic method that takes a type parameter. This interface can be implemented anywhere in a program using a lambda expression instead of creating classes with multiple functions. For eg, to implement a runnable interface used only for multithreading one needs to implement only a run() method. Then there is the comparable interface which can be implemented using compare() method.

Important points:

  • The body of a lambda expression can contain zero, one, or more statements.
  • When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
  • When there is more than one statement, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

These are for single–line lambda expressions having void return type.

Type 1: No Parameter.

Syntax:

() -> System.out.println("Hello");

It takes interface of the following form:

interface Test1
{
    void print()
}

Type 2: Single Parameter.

Syntax:

(p) -> System.out.println(p);

It is not mandatory to use parentheses if the type of that variable can be inferred from the context

It takes interface of the following form:

interface Test2
{
    void print(Integer p)
}

The type and return type of the lambdas are automatically inferred.

Type 3: Multi parameters

(p1, p2) -> System.out.println(p1 + " " + p2);

It is not mandatory to use parentheses if the type of that variable can be inferred from the context

It takes interface of the following form:

interface Test3
{
    void print(Integer p1, Integer p2)
}

The type and return type of the lambdas are automatically inferred.

Now, we are done with discussing out the theoretical concept, now let us come up with the implementation part. So here primarily we will be discussing out the codes for the above three types as discussed above:

Note: forEach() method is of Iterable interface that is used to iterate through a collection. Here it takes an argument of Consumer type interface. This is a functional interface having only one abstract method called accept(). Since it is a functional interface, a lambda expression can be passed.

Hence, if we do conclude out the above 

Example 1: Lambda expression with no parameters

Java




// Java code to illustrate lambda expression
// without parameters
 
// functional interface
// without parameters
interface Test1 {
    void print();
}
 
class GfG {
    // functional interface parameter is passed
    static void fun(Test1 t) { t.print(); }
    public static void main(String[] args)
    {
        // lambda expression is passed
        // without parameter to functional interface t
        fun(() -> System.out.println("Hello"));
    }
}


Output

Hello

Example 2: Type 2 Lambda expression with a single parameter

Java




// Java code to illustrate lambda expression
// with single parameter
 
// functional interface
// with one parameter of Integer type
interface Test2 {
    // The void type and the Integer type
    // is automatically inferred from here
    // and assigned to the lambda expression
    void print(Integer p);
}
 
class GfG {
    // takes lambda expression and a variable of
    // Integer type as arguments
    static void fun(Test2 t, Integer p)
    {
        // calls the print function
        t.print(p);
    }
    public static void main(String[] args)
    {
        // lambda expression is passed
        // with a single parameter
        // lambda expression is mapped to the
        // single argument abstract function in the
        // functional interface Test2
        fun(p -> System.out.println(p), 10);
    }
}


Output

10

Example 3: Type 3 Lambda expression with multi parameters

Java




// Java code to illustrate lambda expression
// with multi parameters
 
// functional interface Test3
// with 2 parameter of Integer type
interface Test3 {
    // The void type and the Integer type
    // is automatically inferred from here
    // and assigned to the lambda expression
    void print(Integer p1, Integer p2);
}
 
class GfG {
    // takes parameter of Test3 type followed
    // by 2 integer parameters p1 and p2
    static void fun(Test3 t, Integer p1, Integer p2)
    {
        // calls the print function
        t.print(p1, p2);
    }
    public static void main(String[] args)
    {
        // lambda expression is passed
        // with two parameters
        // lambda expression is mapped to the
        // double argument abstract function in the
        // functional interface Test3
        fun((p1, p2)
                -> System.out.println(p1 + " " + p2),
            10, 20);
    }
}


Output

10 20

Example 4:Lambda expression with two parameters

Java




// Demonstrate a lambda expression that takes two parameters
 
interface NumericTest2{
   boolean test(int n, int d);
}
 
class GFG{
public static void main(String args[]){
 
  // The lambda expression here determines if one number is the factor of another
  NumericTest2 isFactor= (n,d) -> (n%d)==0;
  if(isFactor.test(10,2))
    System.out.println("2 is the factor of 10");
   
  if(!isFactor.test(10,3))
    System.out.println("3 is not a factor of 10");
   
}
}


Output

2 is the factor of 10
3 is not a factor of 10


Previous Article
Next Article

Similar Reads

Block Lambda Expressions in Java
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". B
4 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Lambda Expressions | Concurrent Programming Approach 4
Prerequisite: Different Approaches to Concurrent Programming in Java Lambda expressions are very similar in behaviour to anonymous inner classes. They have complete access to code from surrounding classes including the private data. They are much more concise, succinct and readable. However, lambda expressions cannot have instance variables, so the
2 min read
Lambda Expressions in Android with Example
Lambda expressions are a feature of Java 8 and later, which can be used in Android development to simplify code and improve readability. They are anonymous functions that can be passed around as values and can be used to create functional interfaces, which are interfaces that have a single abstract method. In Android, lambda expressions can be used
4 min read
Java Lambda Expression with Collections
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: - compare(). An interface that only contains only a single abst
3 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Converting ArrayList to HashMap in Java 8 using a Lambda Expression
A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap. Syntax: (parms1, parms2) -> expressionExamples: Input : List : [1="1", 2="2", 3="3"] Output: Map : {1=1, 2=2, 3=3, 4=4, 5=5} Input : List : [1="I", 2="love
2 min read
Serialization of Lambda Expression in Java
Here we will be discussing serialization in java and the problems related to the lambda function without the serialization alongside discussing some ways due to which we require serialization alongside proper implementation as in clean java programs with complete serialization and deserialization process using the function interface. Serialization
5 min read
Java - Lambda Expression Variable Capturing with Examples
Variable defined by the enclosing scope of a lambda expression are accessible within the lambda expression. For example, a lambda expression can use an instance or static variable defined by its enclosing class. A lambda expression also has access to (both explicitly and implicitly), which refers to the invoking instance of the lambda expression's
4 min read
Java 11 Lambda Features with Examples
In essence, lambda expressions express examples of functional interfaces (a functional interface is an interface with a single abstract method). Java.lang. Runnable is an excellent example. Lambda expressions, which also implement functional interfaces, implement the lone abstract function. In Java 11, lambda expressions were added, and they offer
3 min read
Article Tags :
Practice Tags :