Search code examples
javalambdasyntaxjava-8

How to covert the follow code to lambda expression?


I'm learning lambda, and I know the 3 steps rule which is:

  1. Removing the method name
  2. Removing the parameter types
  3. Removing the return statement


MyInterface myInterface = new MyInterface() 
{
    @Override
    public void printMe(String message) {
        System.out.println(message);
    }
};

Is the answer

MyInterface myInterface = new MyInterface(message -> message);

Or

MyInterface myInterface = message -> System.out.println(message);

Or I maybe all wrong...?


Solution

  • The second option is correct. But note you could clean the code up even further by using method references:

    MyInterface myInterface = System.out::println;