Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using lambda expressions in java 8?

Interface AccountService{
    public void createAccount();
}

AccountService accountServiceAnonymous = new AccountService(){
    public void createAccount(){
        Account account = new Account();
        save(account);
    }
};

AccountService accountServiceLambda = () -> {
    Account account = new Account();
    save(account);
}

Apart from reduced number of lines of code, are there any other advantages of using lambda expressions in java 8 ?

like image 235
Prasad Revanaki Avatar asked Nov 03 '15 05:11

Prasad Revanaki


People also ask

What are the advantages of lambda expression in Java?

Benefits of Lambda Expression One of the benefits of using lambda expression is the reduced amount of code. See the example below. In this case, we are not passing any parameter in lambda expression because the run() method of the functional interface (Runnable) takes no argument.

What are advantages of using lambda function?

AWS Lambda allows you to integrate your application server needs with mass-mailing services such as SES. Thus, you can consolidate more of the functionality your team requires to operate under one house. This not only reduces administrative costs but also makes your team's workflow more streamlined and efficient.

Why do we need lambda expressions in Java 8?

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .

What are the advantages of lambda expression over anonymous methods?

Concise code, more readability, less ceremony to do simple things i.e. replacement of anonymous class (you still have to write an anonymous class, in case of lambda you don't have to write a class). Reuse of code, create lambda expressions and pass it around methods.


4 Answers

Adding to what @Bilbo has mentioned in comments. In Java 1.7 there was a new JVM Opcode was released named invokedynamic and Java 8 Lambda uses this. So the following code will result in an Anonymous class being created when you compile the code. Possible <ClassName>$1.class so if you have 10 anonymous classes that is 10 more classes in the final jar.

AccountService accountServiceAnonymous = new AccountService(){
    public void createAccount(){
        Account account = new Account();
        save(account);
    }
};

But Java 8 lambda uses invokedynamic to call lambdas thus if you have 10 lambdas it will not result in any anonymous classes thus reducing the final jar size.

AccountService accountServiceLambda = () -> {
    Account account = new Account();
    save(account);
}
like image 181
shazin Avatar answered Oct 19 '22 19:10

shazin


Another advantage of lambdas (and method references) is visible when you combine them with Stream API and other features added in Java 8, e.g. Optional.

Consider this code:

private void pushToFront(AbstractInfo contactInfo) {
        registeredWindows.stream()
            .filter(window -> window.getWindowId() == contactInfo.getId())
            .findAny()
            .ifPresent(Window::pushToFront);
    }

The method filters the list of registered windows matching windowId with contact's id returning an Optional. If the list contains window with matching id, then the value in Optional is present and pushToFront method is then on it. Compare this to the same functionality but written in Java 7:

private void pushToFront(AbstractInfo contactInfo) {
    for (Window window : registeredWindows) {
        if (window.getWindowId() == contactInfo.getId() {
            window.pushToFront();
        }
    }
}

The code with lambda expression, stream and method reference, at least to me, is more concise and readable (when you get use to using streams). The example above is quite simple - but consider one, which in Java 7 would require nested loops, multiple conditional statements etc. Not easy to read even harder not to loose track of what's going on.

Lambdas then allow one to fully utilize other neat features of the Java 8 which among others result in neat, clean, efficient and easy to understand code.

Bottom line is, you should consider lambda expressions as part of a larger whole which are great for themselves but even better when combined with other 'building blocks' of Java 8.

like image 34
ttarczynski Avatar answered Oct 19 '22 19:10

ttarczynski


One more - unlike anonymous classes, lambdas do NOT create a new scope, they share the same scope as the enclosing block/environment.

So:

  1. It's easier to access the enclosing object - plain this reference refers to the instance of the enclosing class (and you don't need to say EnclosingClass.this)

  2. There are no shadowing issues (as you cannot define local variables with the same names as variables in the enclosing scope)

like image 7
Ashutosh A Avatar answered Oct 19 '22 18:10

Ashutosh A


Advantages of lambda expressions

  1. It reduces the lines of code.
  2. It supports sequential and parallel execution by passing behavior in methods with collection stream API.
  3. Using Stream API and lambda expression we can achieve higher efficiency (parallel execution) in the case of bulk operations on collections.
like image 7
Anand Sinha Avatar answered Oct 19 '22 18:10

Anand Sinha