Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Java 8 lambda with a single parameter

I want to simply pass a lambda (chunk of code) and execute it when I need to. How do I implement the method executeLambda(...) in the code below (as well what is the method signature):

public static void main(String[] args)
{
    String value = "Hello World";
    executeLambda(value -> print(value));
}

public static void print(String value)
{
    System.out.println(value);
}

public static void executeLambda(lambda)
{
    someCode();
    lamda.executeLambdaCode();
    someMoreCode();
}
like image 629
Stephane Grenier Avatar asked Dec 06 '22 13:12

Stephane Grenier


2 Answers

Your lambda takes one parameter, but you only pass the lambda to executeLambda, not the value. If you want the lambda to capture the local variable, don't write it taking a parameter, but if you do really want it to take one parameter, you would write it like this:

import java.util.function.Consumer;

public static void main(String[] args) {
    String message = "Hello World";
    executeLambda(message, value -> print(value));
}

public static void executeLambda(String value, Consumer<String> lambda) {
    lambda.accept(value);
}

If you want it to capture the value, then use Runnable, write the lambda as () -> print(value), and call it like runnable.run().

like image 79
David Conrad Avatar answered Dec 30 '22 15:12

David Conrad


public static void main(String[] args)
{
    String value = "Hello World";
    executeLambda(() -> print(value));
}

public static void print(String value)
{
    System.out.println(value);
}

public static void executeLambda(Runnable runnable)
{
    runnable.run();
}
like image 43
yelliver Avatar answered Dec 30 '22 16:12

yelliver