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

Lambda Expression in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Lambda expressions in Java, introduced in Java SE 8, represent instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code.

Functionalities of Lambda Expression in Java

Lambda Expressions implement the only abstract function and therefore implement functional interfaces lambda expressions are added in Java 8 and provide the below functionalities.

  • Functional Interfaces: Lambda expressions implement single abstract methods of functional interfaces.
  • Code as Data: Treat functionality as a method argument.
  • Class Independence: Create functions without defining a class.
  • Pass and Execute: Pass lambda expressions as objects and execute on demand.

Lambda expressions allow for cleaner and more efficient code, especially in functional programming. To dive deeper into lambda expressions and understand how to apply them in real-world applications, the Java Programming Course offers detailed lessons with hands-on practice

Java Lambda Expression Example

Functional Interface Example:

Java
// Java program to demonstrate lambda expressions
// to implement a user defined functional interface.

// A sample functional interface (An interface with
// single abstract method
interface FuncInterface
{
    // An abstract function
    void abstractFun(int x);

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

class Test
{
    public static void main(String args[])
    {
        // lambda expression to implement above
        // functional interface. This interface
        // by default implements abstractFun()
        FuncInterface fobj = (int x)->System.out.println(2*x);

        // This calls above lambda expression and prints 10.
        fobj.abstractFun(5);
    }
}

Output
10

lambda expressionLambda Expression Syntax

 lambda operator -> body

Lambda Expression Parameters

There are three Lambda Expression Parameters are mentioned below:

  1. Zero Parameter
  2. Single Parameter
  3. Multiple Parameters

1. Lambda Expression with Zero parameter 

() -> System.out.println("Zero parameter lambda");

2. Lambda Expression with Single parameter

(p) -> System.out.println("One parameter: " + p);

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

ArrayList Example:

Java
// A Java program to demonstrate simple lambda expressions
import java.util.ArrayList;
class Test {
    public static void main(String args[])
    {
        // Creating an ArrayList with elements
        // {1, 2, 3, 4}
        ArrayList<Integer> arrL = new ArrayList<Integer>();
        arrL.add(1);
        arrL.add(2);
        arrL.add(3);
        arrL.add(4);

        // Using lambda expression to print all elements
        // of arrL
        arrL.forEach(n -> System.out.println(n));

        // Using lambda expression to print even elements
        // of arrL
        arrL.forEach(n -> {
            if (n % 2 == 0)
                System.out.println(n);
        });
    }
}

Output
1
2
3
4
2
4

Note: that lambda expressions can only be used to implement functional interfaces. In the above example also, the lambda expression implements Consumer Functional Interface. 

3. Lambda Expression with Multiple parameters

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

Lambda Expression with Functional Interfaces

Example with FuncInter1 Interface:

A Java program to demonstrate the working of a lambda expression with two arguments. 

Java
@FunctionalInterface
interface FuncInter1 {
    int operation(int a, int b);
}

public class Test {

    public static void main(String[] args) {
        // Using lambda expressions to define the operations
        FuncInter1 add = (a, b) -> a + b;
        FuncInter1 multiply = (a, b) -> a * b;

        // Using the operations
        System.out.println(add.operation(6, 3));  // Output: 9
        System.out.println(multiply.operation(4, 5));  // Output: 20
    }
}

Output
9
20

Note: Lambda expressions are just like functions and they accept parameters just like functions. 

Additional Examples

Default Functional Interfaces:

  • Comparable<T>: int compareTo(T o);
  • Comparator<T>: int compare(T o1, T o2);

These are commonly used in sorting and comparisons.

Conclusion

Some Important points intake from this article is mentioned below:

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

Lambda Expression – FAQs

What type of lambda expression Java?

Java Lambda Expressions are the short block of code that accepts input as parameters and returns a resultant value.

Is it good to use lambda expressions in Java?

Yes, using lambda expressions makes it easier to use and support other APIs.

What are the drawbacks of Java lambda?

Java lambda functions can be only used with functional interfaces.

Based on the syntax rules just shown, which of the following is/are NOT valid lambda expressions?

  1. () -> {}
  2. () -> “geeksforgeeks”
  3. () -> { return “geeksforgeeks”;}
  4. (Integer i) -> return “geeksforgeeks” + i;
  5. (String s) -> {“geeksforgeeks”;}

4 and 5 are invalid lambdas, the rest are valid. Details:

  1. This lambda has no parameters and returns void. It’s similar to a method with an empty body: public void run() { }.
  2. This lambda has no parameters and returns a String as an expression.
  3. This lambda has no parameters and returns a String (using an explicit return statement, within a block).
  4. return is a control-flow statement. To make this lambda valid, curly braces are required as follows: (Integer i) -> { return “geeksforgeeks” + i; }.
  5. “geeks for geeks” is an expression, not a statement. To make this lambda valid, you can remove the curly braces and semicolon as follows: (String s) -> “geeks for geeks”. Or if you prefer, you can use an explicit return statement as follows: (String s) -> { return “geeks for geeks”; }.


Previous Article
Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg