1

Ι have the following custom Runnable:

class RandomSum extends Runnable {

   public void run() {
     float sum - 0;
     for(int i = 0; i<1000000;i++){
       sum+=Math.random();
     } 
   }
}

And I want to run it like that:


  RandomSum s =new RandomSum();
  s.retrieveCallback((sum)->{
    System.out.println(sum);
  });
  Thread thread = new Thread();
  thread.start();

But I do not know how I should define the method retrieveCallback in RandomSum that accepts a lambda?

2
  • Where do you want to execute the lambda in RandomSum class? Do you want to print the sum after the for loop? Commented Apr 10, 2021 at 12:47
  • Actually I want to pass the sum in a lamnda therefore yes I want to do it after the for loop. Commented Apr 10, 2021 at 12:48

2 Answers 2

1

You can define retrieveCallback within RandomSum as follows:

public void retrieveCallback(FeedbackHandler feedbackHandler) {
    int sum = ...; // Get the value however you like.
    feedbackHandler.handleFeedback(sum);
}

And then define this FeedbackHandler interface as:

public interface FeedbackHandler {
    void handleFeedback(int sum);
}

Essentially what happens when you pass lambda (sum) -> {...} to retrieveCallback is:

retrieveCallback(new FeedbackHandler() {
    @Override
    public void handleFeedback(int sum) {
        ...
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

IC A lambda actually is a sinlgle-method anomymous class right?
Yes, where it is important that only one method can possibly match the signature that you pass in. Note that (int sum) -> {} is also possible (specifying the type of the argument), and that a lambda that returns something can be either (...) -> returnVal or (...) -> { ...; return returnVal; }
1

One possible target type of the lambda you've shown is a Consumer. Define a method setCallback accepting a Consumer<Float> and store it as an instance variable. Then invoke it after the for loop.

class RandomSum implements Runnable {
    Consumer<Float> callback;
   
    public void setCallback(Consumer<Float> callback) {
        this.callback = callback;
    }

    public void run() {
        float sum = 0;
        for(int i = 0; i<1000000;i++){
            sum += Math.random();
        } 
        callback.accept(sum);
    } 
}

Caller side

RandomSum s =new RandomSum();
s.setCallback((sum)->{
    System.out.println(sum);
});

Or using method references,

s.setCallback(System.out::println);

Preferably you can pass the callback in the constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.