Lambda Expression Basics and Syntax – Java8

Lambda Expression Basics Java8

In simple term, a Lambda Expression is implementation of a Functional Interface. Lambda Expression is a way to provide implementation of a functional interface without creating a Class or Anonymous Inner Class. Note that Lambda can implement only a functional interface.

Read more about Functional Interface

Here is a functional interface named Processor which has single abstract method called process

Processor.java
package com.readtorakesh.java8.lambda_expression_basics;

@FunctionalInterface
public interface Processor {
    int process(int input);
}

And let say there is processValue method, which takes a value and a Processor object as input, apply processor on the value and return the result.

private int processValue(int value, Processor processor) {
 return processor.process(value);
}

Call processValue method using Anonymous Inner Inner Class as implementation of Processor interface.

processValue(10, new Processor() {
 @Override
 public int process(int input) {
  return input * 2;
 }
});

It’s easily noticeable the unnecessary verbose code that we had to write for anonymous inner class. Only important line which is doing real work is return input * 2. Rest every thing is overhead ceremonial code. With Lambda expression all that unnecessary code can be easily avoided and end result is even more readable code.

Call processValue method using Lambda Expression.

processValue(10, n -> n * 2);

Notice the second input parameter to processValue method. It’s lambda expression implementing Processor.process method, quite easily readable that it’s doing double of n the input value.

With Lambda expression we can easily provide another implementation of Processor.process method. See below another implementation which divides input value by 2

processValue(10, n -> n / 2);

Here is main program showing Anonymous Inner Class v/s Lambda implementation of Processor interface.

MainApp.java
package com.readtorakesh.java8.lambda_expression_basics;

public class MainApp {
    public static void main(String[] args) {
        new MainApp().doMain();
    }
    
    private void doMain() {
        System.out.println("# Lambda - Double the value: 10");
        System.out.println(processValue(10, n -> n * 2));
        
        System.out.println("\n");
        
        System.out.println("# Anonymous Inner Class - Double the value: 10");
        System.out.println(processValue(10, new Processor() {
            @Override
            public int process(int input) {
                return input * 2;
            }
        }));
    }
    
    private int processValue(int value, Processor processor) {
        return processor.process(value);
    }
}

 

Output
# Lambda - Double the value: 10
20


# Anonymous Inner Class - Double the value: 10
20

 

Type Inference magic of Lambda

If a class implements an interface it has to specify what interface it’s implementing, implemented method, input parameter and return type etc. However with lambda expression these things are often inferred automatically and it’s not required to specifically mention them.

The method signature, where lambda is passed, infers type of the interface being implement by lambda expression. For example if we pass lambda expression in second parameter of following method, it is inferred that lambda implements Processor interface

int processValue(int value, Processor processor)

Since lambda implements only functional interface (Single Abstract Method) the implemented method name can also be inferred and then parameter and return type can also be inferred using method signature. For example, for the second parameter of above processValue method lambda will implement process method of the interface, which takes int as input and returns int as well.

Lets talk about syntax of lambda expression.

Lambda Expression Parameter

When implemented interface’s method (SAM) taken single parameter then parenthesis is optional

n -> n * 2

If method takes no parameter or more than one parameter parenthesis is required

(n1, n2) -> n1 * n2
() -> System.out.println(“no parameter method implementation”)

Lambda Expression Body

If lambda body (method implementation) has only single line then use of curly braces to enclose the body is optional. You can remove curly braces.

n -> n * 2

If lambda body has more than one line then you must enclose body within curly braces.

n -> {
 int factor=2;
 return n * factor;
}

Lambda Expression Return Type

If lambda body has more than one line then you have enclose it with curly braces and use standard return statement to return value.

n -> {
 int factor=2;
 return n * factor;
}

If lambda body is just one line then you can return value as below

n -> return n * 2;

And in this case return keyword is option as well so you can drop return keyword

n -> n * 2

It is understood to the compiler that output of the calculation is the return value.

That’s all about basic of Lambda expressions in Java8. I hope now you can try your hands on Lambda and make use of it in your code.

Download Code

You can download complete source code referred in this blog with gradle project here.
https://github.com/rakeshprajapati1982/lambda-expression-basics

Further Reading

Please share it and help others if you found this blog helpful. Feedback, questions and comments are always welcome.

Comments