Java Lambda Expression

Introduction to Java 8 Lambda expression

Java 8 Lambda expression (or function) is an anonymous function. Anonymous function means the function who do not have name and it is not bound to any class.
Lambda expression is the shorter form of method writing. Using java 8 lambda expression we can remove the obvious and redundant code from functional interface implementation. Compiler can assume code such as : Class name, method signature, Argument types, return keyword, etc. In this blog we will learn with various Java 8 Lambda expression implementation examples.
There are many other changes in java 8 which you should read about java 8 features with examples.

Java Lambda Expression Syntax

Java Lambda expressions are very simple and contains three parts. Parameters(method arguments), arrow operator and expressions(method body).
Syntax: (parameters) -> { statements; }

As any java function we can have any number of parameters. We can also have any number of lines or expressions in body.

Example :

//Normal function
Public int add(int a, int b) {

Return a+b;


//Equivalent Java Lambda Expression example
(a,b) -> a+b;

For better understanding lets have look at real life example of Runnable class.

Before java 8, for any functional interface or any class object, we has either implement the class or use anonymous inner class. But after lambda we can remove this overhead.

// before java 8 with implementation
public class RunnableImpl implements Runnable {

public void run(){

System.out.println("Runnable implementation");


usage == >
Runnable runnableObject = new RunnableImpl ();

//Anonymous class implementation
Runnable runnableObject = new Runnable() {


public void run() {

System.out.println("Anonymous implementation");



Let create Lambda expression for equivalent functionality.

As we know Runnable interface is having only abstract method. For every method, signature is always fixed as defined in interface, so we can remove it.
Only the method body will be different as per the requirement so we have to write it

Runnable runnableObject = new Runnable() {      // for Runnable it obviously new Runnable()


public void run(){       // Method syntax is fix

System.out.println("Anonymous implementation");


The equivalent java 8 lambda expression example is,

Runnable runnableObject = () -> { System.out.println("Anonymous implementation") };

This is very basic example, however in real time applications we need to create this many times for threads, comparators, action listeners, etc. This makes code ugly. We can solve this using Java 8 lambda feature.

Things to know about Java lambda expressions:

  • Java 8 lambda expression can have zero, one or any number of arguments [eg: () -> 10; a -> a*a; (a, b) -> a + b; ]
  • For zero or more than one arguments parentheses are mandatory [eg: () -> 10; a -> a*a; (a, b) -> a + b; ]
  • For one argument parentheses are optional [eg: a -> a*a; OR (a) -> a* b; ]
  • Arguments type can be declared or auto detected [eg: (int a, int b) -> a + b; OR (a, b) -> a + b; ]
  • If we want to declare argument types, parentheses are mandatory [eg: a -> a * a; (int a) -> a*a; ]
  • For single line of expression curly brackets are optional [eg: a -> a*a; OR a -> { return a*a }; ]
  • For single line of expression return keyword is optional [eg: a -> a*a; OR a -> { return a*a }; ]
  • If we add curly brackets return keyword is required [eg: a -> a*a; OR a -> { return a*a }; ]
  • Method or class level variables can be used in Lambda expression
  • Local variables used in Java 8 lambda expressions must be effective final variables 

Any variable once initialized and whose value never changes, is called as effectively final variable. For more details about effectively final variable effectively-final in java OR effectively-final by oracle community

Lambda expression Rules

Multiple parameters and multiple lines in body(param1,param2) -> { statement1;statement2; }(a,b,c) -> { int sum= a+b; return sum*c }
Single parameter and multiple lines in bodyparameter -> { statement1;statement2; } id -> { int sqr=n*n; return sqr;}
Single parameter and single Line expressionparameter -> expressionn-> n*n;
Multiple parameters and single Line expression(param1,param2) -> expression(a,b) -> a+b;
no parameter and single Line expression() -> expression() -> "success";
no parameter and multiple Line expressions() -> { statement1;statement2; }() -> { String name = getUserName(); print(name);}

Java 8 Lambda Expression Usage

Some most common usage of java lambda expressions are in stream and optional APIs.

Filter on stream or optional object

Filter is very basic and frequent operation that allows to filter data with some conditions.

//Filter in optional [more details]
Optional nameOptional = Optional.of(“stacktraceguru”);
Optional output = nameOptional.filter(value -> value.equals(“Java 8”));
//Filter in stream [more details]
List dataList = ... -> d.length() > 5);

Map on stream or optional object
Map operation is used to transform object from one form to other. This is very useful method in stream and optional

//Map in optional [more details]
Optional person = ...
Optional name = -> o.getName());
//Map in stream [more details]
List person = ...
List names = -> o.getName()).collect(Collectors.toList());

There are many usage of java lambda expression examples . In real time development we can use lambda expression for many times.

More java lambda expression examples of how to write for any function

Without LambdaWith LambdaDescription
Int add(int a, int b){
return a+b;
(a,b) -> a+b;Function for returning addition of two numbers
Int square(int a){
return a*a;
 a -> a*aFunction for calculating square of number
Void print(String message){
System.out.println (message)
(msg)->System.out.println(msg)Function for printing message on console
Void test(){
System.out.println ("working")
() -> System.out.println ("working")Function for printing test message

Fast track reading :

  • Java 8 Lambda expression (or function) is an anonymous function
  • Removes the obvious code from implementation
  • Syntax: (parameters) -> { statements; }
  • Can have any number of parameters and any number of lines or expressions in body
  • For one arguments parentheses are optional
  • For single line of expression curly brackets and return keywords is optional
  • Local variables used in lambdas expressions must be effective final variables


    1. Thank you very much for taking time to read and appreciate the efforts. This motivates us to keep up our work!! Stay tuned for more such interesting blogs. Hope you like them as well!!

Leave a Reply

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