Lambda Expressions – Java 8

Reading Time: 2 minutes

Lambda expressions is a new and important feature of Java which started rolling from JAVA 8. It provides a clear and concise way to represent a method interface using an expression.

  • Lambda Expression is very useful in collection framework. It helps to iterate, filter and extract data from collection.
  • The Lambda expression provides the implementation of an functional interface.
  • It saves a lot of code.
  • In case of lambda expression, we don’t need to define the method again for providing the implementation. Here, we just write the implementation code.
  • Java treats Lambda expression as a function and hence there is no .class generation

Why Lambda Expressions?

It provides the following functionalities –

  • We can create a function that does not belongs to any class.
  • We can pass an Expression around as an object and can execute on demand.
  • It enables us to treat functionality as a method argument, or code as data.


Code Example

interface FunctionalInterface
{
    // abstract function
    void abstractFun(int x);
}


public class FunctionalInterfaceImplementation
{
    public static void main(String...args)
    {
        // lambda expression to implement above
        // functional interface. This interface
        // by default implements abstractFun()
        FunctionalInterface demo = (int x)->System.out.println(2*x);
  
        // This calls above lambda expression and prints 10.
        demo.abstractFun(5);
    }
}


Syntax

 lambda operator -> body

where operator can have:

  • Zero Parameter
() -> System.out.println("Lambda with zero arguments");
  • One Parameter- It is not mandatory to use parentheses, if the type of that variable can be inferred from the context
(p) -> System.out.println("Parameter: " + p);
  • Multiple Parameters :
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
Lambda Expression Syntax Explaination

Demonstration : Lambda Expressions (Print even numbers in an ArrayList)

import java.util.ArrayList;
class LambaExpressions
{
    public static void main(String...args)
    {
        // Creating an ArrayList with elements
        // {5,6,7,8}
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
  
        // Using lambda expression to print even elements
        // of list
        list.forEach(n -> { if (n%2 == 0) System.out.println(n); });
    }
}

Reference Links :

Written by 

Prakhar is a Software Consultant at Knoldus . He has completed his Masters of Computer Applications from Bharati Vidyapeeth Institute of Computer Applications and Management, Paschim Vihar . He likes problem solving and exploring new technologies .

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading