Summary of Different Syntaxes to Write Lambda Expressions in Java 8

Java 8 allows you to write lambda expressions in few varying syntaxes. Let us quickly see those here.

 

With no arguments

Runnable r = () -> System.out.println(“H”);

 

Only one argument: with or without parenthesis

ActionListener al1 = (event) -> System.out.println(“Button clicked”);

ActionListener al2 = event -> System.out.println(“Button clicked”);

 

Block of code: Need parenthesis

Runnable r = () -> { 

 System.out.print(“Hello ”);

 System.out.print(“World”);

};

 

Methods that take more than one args

BinaryOperator<Long> add   = (x,y) -> x+y;

 

Explicitly using the type

BinaryOperator<Long> add = (Long x, Long y) -> x+y;

 

Implicit vs. Explicit return

Return type is not needed for one line statement lambda expressions.

For a block of code with paranthesis, it will be required.

 

Encapturing Lambda

A lambda expression that uses a variable from the enclosing scope (e.g. method argument).

However, these variables should be effectively final.

 

TODO:

  • Give examples where explicit typing may be required.

  • Lambda expression for a functional interface that throws exception.

  • Give example for method paameterization: method that has an argument of type a functional interface, can receive a lambda expression.

  • Give example for implicit and explicit return.

  • Lambda expression that uses this, super etc. for accessing variables. Should these be effectively final?

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!