You are on page 1of 16

why use Lambda Expression

To provide the implementation of Functional interface.

Less coding.

Java Lambda Expression Syntax

(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of


expression.

3) Body: It contains expressions and statements for lambda


expression.

No Parameter Syntax

() -> {

//Body of no parameter lambda

}
(p1) -> {

//Body of single parameter lambda

Two Parameter Syntax

(p1,p2) -> {

//Body of multiple parameter lambda

Let's see a scenario where we are not implementing Java lambda


expression. Here, we are implementing an interface without using
lambda expression.

Without Lambda Expression

interface Drawable{

public void draw();

public class LambdaExpressionExample {

public static void main(String[] args) {

int width=10;

//without lambda, Drawable implementation using


anonymous class
Drawable d=new Drawable(){

public void draw(){System.out.println("Drawing "+width);}

};

d.draw();

Java Lambda Expression Example

Now, we are going to implement the above example with the help
of Java lambda expression.

@FunctionalInterface //It is optional

interface Drawable{

public void draw();

public class LambdaExpressionExample2 {

public static void main(String[] args) {

int width=10;

//with lambda

Drawable d2=()->{

System.out.println("Drawing "+width);
};

d2.draw();

Java Lambda Expression Example: No Parameter

interface Sayable{

public String say();

public class LambdaExpressionExample3{

public static void main(String[] args) {

Sayable s=()->{

return "I have nothing to say.";

};

System.out.println(s.say());

Java Lambda Expression Example: Single Parameter

interface Sayable{

public String say(String name);


}

public class LambdaExpressionExample4{

public static void main(String[] args) {

// Lambda expression with single parameter.

Sayable s1=(name)->{

return "Hello, "+name;

};

System.out.println(s1.say("Sonoo"));

// You can omit function parentheses

Sayable s2= name ->{

return "Hello, "+name;

};

System.out.println(s2.say("Sonoo"));

Java Lambda Expression Example: Multiple Parameters

interface Addable{
int add(int a,int b);

public class LambdaExpressionExample5{

public static void main(String[] args) {

// Multiple parameters in lambda expression

Addable ad1=(a,b)->(a+b);

System.out.println(ad1.add(10,20));

// Multiple parameters with data type in lambda expression

Addable ad2=(int a,int b)->(a+b);

System.out.println(ad2.add(100,200));

Java Lambda Expression Example: with or without return


keyword

In Java lambda expression, if there is only one statement, you


may or may not use return keyword. You must use return
keyword when lambda expression contains multiple statements.

interface Addable{

int add(int a,int b);


}

public class LambdaExpressionExample6 {

public static void main(String[] args) {

// Lambda expression without return keyword.

Addable ad1=(a,b)->(a+b);

System.out.println(ad1.add(10,20));

// Lambda expression with return keyword.

Addable ad2=(int a,int b)->{

return (a+b);

};

System.out.println(ad2.add(100,200));

Java Lambda Expression Example: Foreach Loop

import java.util.*;

public class LambdaExpressionExample7{

public static void main(String[] args) {


List<String> list=new ArrayList<String>();

list.add("ankit");

list.add("mayank");

list.add("irfan");

list.add("jai");

list.forEach(

(n)->System.out.println(n)

);

What New Features Did Java 8 Include?

There are various new features in Java 8, but the following are the most important:

1. Lambda Expressions −a new feature of the language that allows us to consider actions

as objects

2. Method References − allow us to define Lambda Expressions by explicitly referring to

methods by their names

3. Optional − Optionality is expressed via a special wrapper class.

4. Functional Interface – A Lambda Expression can be used to implement an interface

with a maximum of one abstract method.


5. Default methods − allow us to provide entire implementations in interfaces in addition

to abstract methods

6. Nashorn, JavaScript Engine − JavaScript code execution and evaluation engine based

on ava.

7. Stream API −a particular iterator class that lets us to efficiently process collections of

items

8. Date API −a Date API inspired by JodaTime that is enhanced and immutable

What are functional or SAM interfaces?

An interface with only one abstract method is known as a functional interface. As a result,

it's also known as the SAM (Single Abstract Method) interface. Because it covers a function as

an interface, or in other words, because a function is represented by a single abstract method

of the interface, it's called a functional interface.

Default, static, and overridden methods can all be found in functional interfaces. The

@FunctionalInterface annotation can be used to declare Functional Interfaces. This annotation

will cause a compiler error if it is used on interfaces with more than one abstract method.

@FunctionalInterface

interface Square {

int calculate(int x);

class Test {

public static void main(String args[])

int a = 5;
// lambda expression to define the calculate method

Square s = (int x) -> x * x;

// parameter passed and return type must be

// same as defined in the prototype

int ans = s.calculate(a);

System.out.println(ans);

Lambda expression is a new feature which is introduced in Java 8. A lambda expression is an anonymous
function. A function that doesn’t have a name and doesn’t belong to any class. The concept of lambda
expression was first introduced in LISP programming language.

Java Lambda Expression Syntax

To create a lambda expression, we specify input parameters (if there are any) on the left side of the
lambda operator ->, and place the expression or block of statements on the right side of lambda
operator. For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two
arguments x and y and returns the sum of these.

//Syntax of lambda expression

(parameter_list) -> {function_body}

Lambda expression vs method in Java

A method (or function) in Java has these main parts:

1. Name

2. Parameter list

3. Body
4. return type.

A lambda expression in Java has these main parts:

Lambda expression only has body and parameter list.

1. No name – function is anonymous so we don’t care about the name

2. Parameter list

3. Body – This is the main part of the function.

4. No return type – The java 8 compiler is able to infer the return type by checking the code. you need
not to mention it explicitly.

@FunctionalInterface

interface MyFunctionalInterface {

//A method with no parameter

public String sayHello();

public class Example {

public static void main(String args[]) {

// lambda expression

MyFunctionalInterface msg = () -> {

return "Hello";

};

System.out.println(msg.sayHello());

}
@FunctionalInterface

interface MyFunctionalInterface {

//A method with single parameter

public int incrementByFive(int a);

public class Example {

public static void main(String args[]) {

// lambda expression with single parameter num

MyFunctionalInterface f = (num) -> num+5;

System.out.println(f.incrementByFive(22));

Method References in Java 8


The :: operator is used in method reference to separate the class or object from the method name

@FunctionalInterface

interface Display {

void display();

public class Example {

public void myMethod() {


System.out.println("method reference in java 8");

public static void main(String[] args) {

Example obj = new Example();

// Reference to the method using the object of the class myMethod

Display ref = obj::myMethod;

// Calling the method inside the functional interface Display

ref.display();

public static void loopMapClassic() {

Map<String, Integer> map = new HashMap<>();

map.put("A", 10);

map.put("B", 20);

map.put("C", 30);

map.put("D", 40);

map.put("E", 50);

map.put("F", 60);

for (Map.Entry<String, Integer> entry : map.entrySet()) {


System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());

1.2 In Java 8, we can use forEach to loop a Map and print out its entries.

public static void loopMapJava8() {

Map<String, Integer> map = new HashMap<>();

map.put("A", 10);

map.put("B", 20);

map.put("C", 30);

map.put("D", 40);

map.put("E", 50);

map.put("F", 60);

// lambda

map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));

Output
Terminal

Key : A, Value : 10

Key : B, Value : 20

Key : C, Value : 30

Key : D, Value : 40

Key : E, Value : 50

Key : F, Value : 60

forEach() Method In Iterable Interface

In Java 8, the Java.lang interface now supports a “forEach” function. Iterable that can iterate
over the collection’s items. The Iterable interface has a default method called “forEach.”
Collection classes use it to iterate items, which extends the Iterable interface.You may send
Lambda Expression as an argument to the “forEach” method, which accepts the Functional
Interface as a single parameter.

Optional Class

In Java 8, the “java.util” package included an optional class. The public final class “Optional” is used to
handle NullPointerException in a Java program. You may give other code or values to execute using
Optional. Thus, optional reduces the number of null checks required to avoid a nullPointerException.

You may use the Optional class to prevent the application from crashing and terminating unexpectedly.
The Optional class has methods for checking the existence of a value for a given variable.

The following program demonstrates the use of the Optional class.


import java.util.Optional;

public class Main{

public static void main(String[] args) {

String[] str = new String[10];

Optional<String>checkNull =

Optional.ofNullable(str[5]);

if (checkNull.isPresent()) {

String word = str[5].toLowerCase();

System.out.print(str);

} else

System.out.println("string is null");

You might also like