1.

Lambda Expressions in Java 8

Answer»

Lambda expressions in JAVA are expressions which implement functional interfaces. Functional interfaces are those interfaces that have only one abstract method.

These expressions were created to reduce the unwieldy overhead code of an anonymous class. An anonymous class is a local class devoid of a name and is declared and instantiated at the same time.

Until Java 8, even for the simplest of operations, additional syntactical code was written with anonymous classes . Lambda expressions were introduced to remove this shortcoming.

The syntax:

lambda operator->body

lambda operator is an parameter LIST can have 0, 1 or multiple PARAMETERS.

Zero parameter:

()->System.out.println(“I have no argument”);

One parameter:

(arg)->System.out.println(“I have one argument”+arg)

Multiple parameters:

(arg1,arg2)->System.out.println(“I have many arguments”+arg1+“ ”+arg2)

Let us use lambda expression to print even integers from a list:

import java.util.*; public class Example {    public static void main(String args[])    {        List<Integer> list = new ArrayList<Integer>();        for(int i=1;i<=10;i++)  // ADDING 1 to 10 in the integer ArrayList        {            list.add(i);        }       // printing even elements in list using lambda expression        list.forEach(arg -> { if (arg%2 == 0) System.out.println(arg); });    } }

The output is as follows:

$javac Example.java $java Example 2 4 6 8 10


Discussion

No Comment Found