Lambda Expressions in Java – What You Need to Know

In Java 8, Java has introduced functional programming and lambda expressions are Java’s first step into functional programming. The function which can be created without belonging to any class in Java is a lambda expression. Lambda expressions can be passed around as it is an object and can be executed on demand.

Lambda Expressions is a function which allows to pass methods as arguments which makes the code free from lots of boilerplate code. Being an anonymous function, lambda function has no name and while not being finite to an identifier.

The Lambda Functions have no return type declaration, no name and no access modifiers (public, private and protected). Lambda expressions directly allow users to pass functions to code which makes user write code more easily.

Lambda expressions are like an unnamed function given as constant values that are written precisely within the place wherever it’s required. Generally, it is used as a parameter to another function.

The most necessary use of lambda expressions is that they can execute within the context as required and the same lambda expressions can be executed differently in another context. The logic will be the same however results will depend upon the different parameters passed to the function.

Java 8 provides support for lambda expressions only with functional interfaces which is also a new feature introduced in Java. The interface with a single abstract method is called Functional Interface. As there is only one abstract method in a lambda expression, we can use the lambda expressions to that method.

Lambda expressions in Java 8 are usually used for implementing simple event listeners/callbacks and for functional programming with the Java Streams API. Lambda expressions basically express instances of functional interfaces and implement the only abstract function. Therefore Lambda expressions implement functional interfaces.

Lambda expressions can be used for sequential and parallel execution by passing behavior into methods. Lambdas can be considered as an anonymous method with a more compact syntax. As it is not mandatory to specify access modifiers, return type, and parameter types while defining the expression using Lambdas in Java 8.

Syntax of Lambda Expression

Here is a syntax for Lambda Expression:

(parameters) -> expression
or
(parameters) -> { statements; }

Sample example:

package com.javafolder.lambdaxpressiondemo;

public class LambdaExpressionDemo {

  interface booleanTest {
    boolean computeTest(int n);
  }

  public static void main(String args[]) {
    booleanTest isEven = (n) -> (n % 2) == 0;
    booleanTest isNegative = (n) -> (n < 0);

    System.out.println(isEven.computeTest(100)); // <-- true
    System.out.println(isNegative.computeTest(100)); // <-- false
  }
}

Why Lambda Expressions in Java?

There are so many reasons for the introduction of lambda expressions in Java 8. And all of them the most beneficial is that we can easily distribute processing of collection over multiple threads.

Before Java 8, if we need to process the elements, the collection had to be done in parallel. The client code used to perform the necessary steps and not the collection.

Now using lambda expressions and Stream API in Java 8, we can do processing logic of elements into methods provided by collections. And the collection is responsible for parallel processing of elements and not for the client.

Lambda Expressions can enable to treat functionality as a method argument, or code as data. And the Lambda function can be created without belonging to any class. And also the lambda expressions can be passed around as an object and executed on demand.

Highlighting features of Lambda Expressions

Here are the highlighting features of Lambda Expressions:

  • Write fewer lines of code

The benefit and feature of using lambda expressions are we can use the reduced amount of code. It also reduces the boilerplate code. In Java, as we know that lambda can be used only with functional interfaces. So with a functional interface, we can easily apply lambda expression.

In those cases, we do not need to pass any parameter in lambda expressions because the functional interface takes no argument. And by using the lambda expressions, we can skip the curly braces ( { } ) in case of a single statement in the method body but in multiple statements, we should use curly braces.

MyInterface myInterface = (String message) -> {
    System.out.print(message);
};
  • Sequential and parallel execution

Lambdas Expression supports the sequential and parallel execution by passing behavior in methods. Before, Java 8, processing the elements of any collection used to be done by obtaining an iterator from the collection. Then the iterator iterates over the elements and used to process each element.

And for processing the elements in parallel, it used to be done by the client code. But after the introduction of Stream API and Lambda expressions in Java 8, functions can be passed to collection methods. It is now the responsibility of collection to processing the elements either in a sequential or parallel manner.

Stream stream = Stream.of("John", "Krishna", "Alex");
Stream parallelStream = stream.parallel();
  • More efficiency (Utilizing Multicore CPU’s)

More efficiency can be achieved by using the Stream API’s and lambda expressions through parallel execution that is in case of bulk operations on collections. And also lambda expressions can help us to achieve internal iteration of collections prior to external iteration. As we have multicore processors and CPUs, we can use Lambda expressions with these multicore CPU’s to do parallel processing of collections.

  • Functional programming

As Java 8 introduced Lambda Expressions, now Java can be used as functional programming. Functional programming doesn’t do anything different than object-oriented programming, but it helps you to write much easier and easily maintainable codes. With the help of Lambda expressions, we can passcode as data and can pass a function as an argument to another function in Java. This feature of Java 8, increases the power of our program.

List<String> address = Arrays.asList("USA", "India", "Brazil");
        address.stream()
        	.filter(x -> x.startsWith("B"))
        	.forEach(System.out::println)
  • Server-less architecture

With Lambda expressions in Server-less architecture, we can make our code independent of the environment. The small modular code functions that we write are encapsulated in a Lambda. And these Lambda expressions can be executed in a Server-less environment.

  • Lambda Expression as objects

Any lambda expression is an object in Java, as it is an instance of a functional interface. Lambda expression can be assigned to any variable and pass it like any other object in Java.

MyComparator myComparator = (x1, y2) -> return x1 > y2;
boolean result = myComparator.compare(5, 10);

Where to use the Lambda Expression?

We can use Lambda expressions anywhere where there is a target type in Java. So we can use a lambda expression in the variable declarations and assignments, Return statements and Method or constructor arguments.

Related posts:

Lombok in Java – Write Less and Better Code

Leave a Reply

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