Tuesday , November 21 2017
Home / java / Lambda Expressions in Java 8

Lambda Expressions in Java 8

Lambda Expressions in Java is one of the most awaited feature, 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 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 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 data bases on a condition and do some aggregate operation as Lambda Expressions offer us a way to eliminate creation of separate classes and unwanted boiler plate 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 method declaration. Compiler can infer the type of arguments by itself as the value of 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 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 single statement. For single statement method body’s compiler will automatically return value, 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 on 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 is 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 list is a collection of integers, below statement returns sum of squares of all elements present in list.
    int sum = list.stream().map(x ->; x*x).reduce((x,y) ->; x + y).get();
    

How Lamda Expressions internally works:

Compiler create 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 compiler which can take care of it. But don’t jump into using lambdas without getting proper understanding on it, as it may confuse you and will result in more functional errors.

Happy Learning 🙂

About Rajesh Reddy Badam

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates.

Recommended

How to add dynamic files to JTree

In the previous tutorial, we learn about a simple JTree. This tutorial is for adding …

Leave a Reply

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