0% found this document useful (0 votes)
33 views

Zero Parameter:: Lambda Operator - Body

Lambda expressions in Java 8 allow for the creation of anonymous functions that can be passed around and used without being declared. They are similar to functions and can take parameters like functions. The document provides examples of lambda expressions with zero, one, and multiple parameters and demonstrates using them to print elements from an ArrayList. Lambda expressions can only be used to implement functional interfaces and the examples shown implement the Consumer functional interface.

Uploaded by

XYZ Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Zero Parameter:: Lambda Operator - Body

Lambda expressions in Java 8 allow for the creation of anonymous functions that can be passed around and used without being declared. They are similar to functions and can take parameters like functions. The document provides examples of lambda expressions with zero, one, and multiple parameters and demonstrates using them to print elements from an ArrayList. Lambda expressions can only be used to implement functional interfaces and the examples shown implement the Consumer functional interface.

Uploaded by

XYZ Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

28/05/2018 Lambda Expressions in Java 8 - GeeksforGeeks

lambda operator -> body

where lambda operator can be:

Zero parameter:

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

One 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

Multiple parameters :

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

Please note: Lambda expressions are just like functions and they accept parameters just like functions.
// 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
    }
}
Run on IDE

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.

https://www.geeksforgeeks.org/lambda-expressions-java-8/ 2/4

You might also like