Search code examples
javalambdajava-threads

How should I define a lambda in my method's arguments?


Ι 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?


Solution

  • 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) {
            ...
        }
    });