What are the rules for formal parameters in a lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

A lambda expression is similar to a method that has an argument, body, and return type. It can also be called an anonymous function (method without a name). 

We need to follow some rules while using formal parameters in a lambda expression.

  • If the abstract method of functional interface is a zero-argument method, then the left-hand side of the arrow (->) must use empty parentheses.
  • If the abstract method of functional interface is a one-argument method, then the parentheses are not mandatory.
  • If the abstract method of functional interface is a multiple argument method, then the parentheses are mandatory. The formal parameters are comma-separated and can be in the same order of the corresponding functional interface.
  • The mentioning type of formal parameters is not mandatory. In case we have not mentioned the type of formal parameters, then it's type can be determined by the compiler from the corresponding Target Type.

Example

interface Message {
   String hello(String message, String name, Gender gender);
}
enum Gender {
   MALE, FEMALE
}
public class LambdaFormalParameterTest {
   public static void main(String args[]) {
      Message message = (String msg, String name, Gender gender) -> { // lambda expression
         if(gender == Gender.MALE) {
            return "Hello Mr " + name + ", " + msg;
         } else {
            return "Hello Ms " + name + ", " + msg;
         }
      };
      System.out.println(message.hello("Good Morning!!!", "Adithya", Gender.MALE));
      System.out.println(message.hello("Good Morning!!!", "Ambica", Gender.FEMALE));
   }
}

Output

Hello Mr Adithya, Good Morning!!!
Hello Ms Ambica, Good Morning!!!
raja
Published on 27-Dec-2019 13:35:58
Advertisements