Java Stream How to - Get to know three lambda creation body type syntax








Question

We would like to know how to get to know three lambda creation body type syntax.

Answer

/*from   w w w .  jav a 2  s  .  c o  m*/
public class Main {
  public static void main(String[] args) {
    // No need ( ) and return
    MyCalculator myCalculator = (Integer s1) -> s1 * 2;

    System.out.println("1- Result x2 : " + myCalculator.calcIt(5));

    // No need return
    myCalculator = (Integer s1) -> (s1 * 2);

    System.out.println("2- Result x2 : " + myCalculator.calcIt(5));

    // Need {} and "return" and ;
    myCalculator = (Integer s1) -> {
      return s1 * 2;
    };

    System.out.println("3- Result x2 : " + myCalculator.calcIt(6));
  }
}

interface MyCalculator {
  public Integer calcIt(Integer s1);
}

The code above generates the following result.