Lambda Expressions in Java is one of the most awaited features, which was introduced in Dot Net version 3.5 (2007). They make the programming easier by eliminating the need for anonymous classes in Java.

Lambda Expressions in Java 8:

Since Java is object-oriented language everything is considered as an object. We can pass either primitive types or objects as arguments in Java, but cannot pass the method body as in Functional Programming languages like JavaScript.

In earlier days we used to define anonymous classes as below:

new Thread(new Runnable() {
 @Override
     public void run() {
         System.out.println("Hello world one!");
     }
 }).start();

Using Anonymous classes also, we were able to pass only objects as parameters but we are not actually passing method body.

In the above example, we are creating an object for Runnable interface. Since Runnable is an interface and to create an object for it, we should have implementation bound to it and so we are overriding run() method in implementation. We can see how to change this example as part of the Lambda expressions below.

Lambda Expressions:

To avoid the above limitation and to achieve Functional programming support, Java 8 introduced Lambdas in it. No major changes were introduced in Java from a long period apart from Generics and Annotations and finally, Lambdas broke it. They resemble Closures in JavaScript.

Lambdas are mostly used with Streams over collection because, in those scenarios, we always try to filter the databases on a condition and do some aggregate operation as Lambda Expressions offer us a way to eliminate the creation of separate classes and unwanted boilerplate code.

Lambda Expressions Syntax:

(arguments) ->{body}

Points to note while using lambda expressions:

  • It’s not needed to define the type of arguments as we do in the method declaration. The compiler can infer the type of arguments by itself as the value of an argument.
  • We can have zero, one or more arguments. We have to place parenthesis only when we are passing more than one argument or one argument with the type name
  • It’s not needed to define curly braces if we have a single statement.
  • It’s not needed to place the return value in case of a single statement. For single statement method body’s compiler will automatically return value, the same as the value returned by that single statement

When we start using lambdas, the above way of starting a thread changes to:

new Thread(()-> { System.out.println("Task #2 is running"); };).start();

Examples for Lambda Expressions:

Below are some examples of how we can make use of Lambdas in various scenarios:

  1. Prints Step Executed every time it is executed.
    ()-> System.out.println("Step executed");
  2. Taking two parameters as input and printing value of each parameter.
    (k,v)->System.out.println( key + ", " + value);
  3. If items are a list of employee objects, below statement, prints names of all employees whose age is greater than 40.
    items.stream()  
    .filter(s->s.getAge()> 40)  
    .forEach(System.out.println(s.getName());
  4. If the list is a collection of integers, below statement returns the sum of squares of all elements present in the list.
    int sum = list.stream().map(x ->; x*x).reduce((x,y) ->; x + y).get();

How Lamda Expressions internally works:

Compiler creates a private method for every lambda method body and during runtime, it will be dynamically be called using invokeDynamic() function that was added as part of Java 7.

Lambda Expressions vs Anonymous classes (When to go for what?)

  • If you want to create a constructor, some variables and additional methods apart from what you override. go for Anonymous classes
  • If your interface or body has only one method to be defined go for Lambda Expressions

Conclusion:

Speaking frankly lambda expressions provide a cleaner way of writing code instead of making your programming too formal.
You can write simpler code and leave everything to the compiler which can take care of it. But don’t jump into using lambdas without getting a proper understanding of it, as it may confuse you and will result in more functional errors.

Happy Learning 🙂