Compare Lambda with and without parameters - Java Lambda Stream

Java examples for Lambda Stream:Lambda

Introduction

The syntax of a lambda expression includes

  • an argument list,
  • a new character to the language known as the "arrow token" (->), and
  • a body.

The following model represents the structure of a lambda expression:

(argument list) -> { body } 

The argument list can include zero or more arguments.

If there are no arguments, an empty set of parentheses can be used.

If there is only one argument, then no parentheses are required.

The following code demonstrates a lambda expression that does not contain any arguments:

StringReturn msg = () ->  "This is a test"; 

The StringReturn interface, which is in use by the lambda, is also known as a functional interface.

/** 
 * Functional interface returning a String 
 */ 
 interface StringReturn { 
    String returnMessage(); 
} 

Demo Code

public class Main {

  public static void noArguments() {
    StringReturn msg = () -> "This is a test";
    System.out.println(msg.returnMessage());
  }// w  ww  .  j  a  va 2 s . c om

  public static void returnCode() {
    IntegerReturn code = (codestr) -> {
        return 0;
    };
    System.out.println("Returns: " + code.returnCode("ACTIVE"));

  }

  public static void main(String[] args) {
    noArguments();
    returnCode();
  }
}

/**
 * Functional interface returning a string
 */
interface StringReturn {
  String returnMessage();
}

/**
 * Functional interface returning an int
 */
interface IntegerReturn {
  int returnCode(String codestr);
}

Result


Related Tutorials