Stephane Grenier
Stephane Grenier

Reputation: 15917

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();
}

Upvotes: 7

Views: 27044

Answers (4)

dotrinh DM
dotrinh DM

Reputation: 1393

Passing a byte[] and Runnable like:

public void doSmt(byte[] new_data, Runnable runnable) {
   for (byte datum : new_data) {
            LogI(String.valueOf(datum));
   }
   runnable.run();
}

Call:

byte[] new_data = new byte[10];    
doSmt(new_data, () -> {
     LogI("DA XONG");
});

Upvotes: 0

GhostCat
GhostCat

Reputation: 140407

By providing a reasonable parameter type. The method taking the lambda does not know about lambdas.

Instead you could pass a Callable object. And then your method has to invoke the call() method on that object! Alternatively, a Runnable or Consumer of String could be used (as a Callable is supposed to return a value - and the method you invoke is void).

Upvotes: 1

David Conrad
David Conrad

Reputation: 16359

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().

Upvotes: 14

yelliver
yelliver

Reputation: 5926

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();
}

Upvotes: 4

Related Questions