Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expressions in Java8

import java.util.concurrent.Callable;

public class AdvancedLambda {

    static void invoke(Runnable r){
        r.run();
    }

    static Object invoke(Callable c) throws Exception {
        return c.call();
    }

    public static void main(String[] args) throws Exception {

        String s = (String) invoke(() -> true);
        System.out.println(s);
    }
}

Can anyone help me understand this? I was under the impression that we can only use lamba expressions in Java 8 only when we implement an interface and override its methods (replacing Anonymous classes by Lambda expressions).

Also in which situation will the method invoke(Runnable r) be called?

like image 944
Ashu Avatar asked Nov 12 '15 13:11

Ashu


People also ask

What is the use of lambda expressions in Java?

With the use of Lambda expressions, We will be able to focus on the functional programming ability in java without worrying about objects. With this functional programming ,we can pass only functionality as arguments rather than passing objects or references as parameter. In other words, code can be passed as data.

What is the difference between anonymous classes and lambda expression in Java?

Anonymous classes creates an extra class while lambda expression is converted into a private method. Lambda expression uses invokedynamic byte code instruction from Java 7 to bind this method dynamically.This saves time and memory for us.

Where lambda operator can be used?

where lambda operator can be: Please note: Lambda expressions are just like functions and they accept parameters just like functions. Note that lambda expressions can only be used to implement functional interfaces.

How to add two numbers in a lambda expression?

For example, the given lambda expression takes two parameters and returns their addition. Based on the type of x and y, the expresson will be used differently. If the parameters match to Integer the expression will add the two numbers. If the parameters of type String the expression will concat the two strings. 3.


2 Answers

LambdaParameters -> LambdaBody

The arrow operator (->) for defining lambda functions

  • Lambda :can only be used to execute background tasks (here compiler then figures out)
  • Expressions : are return a value of some kind

Lambda expression is another way of writing an instance of anonymous class, to make an instance of anonymous class easier to write. In JVM, it will not occupy much memory as comparing with normal java object creation with new(executing static variables, static blocks, loading classes from whole hierarchy ).

Lambda expression syntax:

(params) -> expression to implement a @FunctionalInterface

In your test case: String s = (String) invoke(() -> true); the expression has return type true with no argument. So the Runnable FunctionalInterface does not match with lambda expression because it has void run() attribute. It matches with Callable FuncationalInterface using
V call().

How lambda expressions work under the hood?
It might look like the lambda expressions are just the syntax sugar for anonymous inner classes, but there is much more elegant approach. The simplest explanation is: the lambda expression is represented by a new method, and it is invoked at run-time using invokedynamic.

Source Code:

class LambdaExample {

    public void abc() {
        Runnable r = () -> { 
            System.out.println("hello");
        }
        r.run();
    }
    
}

Bytecode equivalent:

class LambdaExample {

    public void abc() {
        Runnable r = <lambda$1 as Runnable instance>;
        r.run(); 
    }

    static void lambda$1() {
        System.out.println("hello");
    }
    
}

Inside the JVM, there is a lambda factory that creates an instance of the functional interface (e.g. Runnable) from the generated lambda method (e.g. lambda$1).

Lambda expressions are great, and there's even more great stuff in Java 8...

like image 189
Premraj Avatar answered Sep 24 '22 02:09

Premraj


only when we Implement a interface and override its methods

That's, more or less, what you do here. Not methods, but just one method: call(). This () -> true part is your implementation of Callable#call().

In other words, this line:

String s = (String) invoke(() -> true);

would be totally equivalent with this one:

String s = (String) invoke(new Callable() {
        @Override
        public Object call() throws Exception {
            return true;
        }
    });    
like image 37
Michal M Avatar answered Sep 25 '22 02:09

Michal M