Home > java > Lambda Expressions in Java with Example

Lambda Expressions in Java with Example

Lambda Expressions in Java

Lambda Expressions in Java with Example

  • Lambda expression basically express instances of functional interfaces.
  • An interface which contains only one abstract method, is called functional interfacejava.lang.Runnable is functional interface.
  • Lambda expressions is the main feature of Java 8.

Why use Lambda Expression:

  1. To provide the implementations of Functional interface.
  2. Less coding required.

Java Lambda Expression Syntax

(argument-list) -> {body}

Without Lambda Expression

interface Draw
{ 
public void draw(); 
} 
public class Main 
{ 
public static void main(String[] args)
{ 
int width=10; 

//without lambda, Drawable implementation using anonymous class 
Draw d=new Draw()
{ 
public void draw(){System.out.println("Drawing "+width);} 
}; 
d.draw(); 
} 
}

OUTPUT

Drawing 10

Lambda Expression Example with No Parameter

@FunctionalInterface  //It is optional  
interface Trans
{
public void trans();
}
public class Main
{
public static void main(String args[])
{
int d=19;
////with lambda Expression
Trans t=()->{
System.out.println("Bus: "+d);
};
t.trans();
}
}

OUTPUT

Bus:19

Lambda Expression Example With  Parameters

interface Add
{
int add(int a,int b);
}

public class Main
{
public static void main(String args[])
{
// Multiple parameters in lambda expression 
Add a1=(a,b)->(a+b);
System.out.println("ADD1: "+a1.add(100,200));

// Multiple parameters with data type in lambda expression
Add a2=(int a,int b)->(a+b);
System.out.println("ADD2: "+a1.add(500,300));

}
}

OUTPUT

ADD1: 300
ADD2: 800

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 Demo_Return
{
String demo(String msg);
}

public class Main
{
public static void main(String args[])
{
Demo_Return dr=(msg)->{

String s1="Welcome ";
return s1+msg;
};

System.out.println(dr.demo("Back"));
}
}

OUTPUT

Welcome Back

Related Topices :-
Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *