Java 8 Lambda Expressions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(176 intermediate revisions by the same user not shown)
Line 7: Line 7:
* [[java#Java8|Java]]
* [[java#Java8|Java]]
* [[Functional Programming]]
* [[Functional Programming]]
=TODO=
* https://blogs.oracle.com/javamagazine/behind-the-scenes-how-do-lambda-expressions-really-work-in-java


=Overview=
=Overview=


Java 8 introduces [[Programming#Functional_Programming|functional programming]] features, in the form of lambda expressions. Lambda expressions allow [[Functional_Programming#Behavior_Parameterization|behavior parameterization]] -  [[Functional_Programming#Function|functions]] can be now assigned to variables, as [[Java_Language#Values|values]], and passed around, which essentially means passing code around. Functions come in form of [[#Lambda_Expression|lambda expressions]] (anonymous functions) or [[#Method_Reference|method references]].
Java 8 introduces [[Programming_Languages_Concepts#Functional_Programming|functional programming]] features, in the form of lambda expressions. Lambda expressions allow [[Functional_Programming#Behavior_Parameterization|behavior parameterization]] -  [[Functional_Programming#Function|functions]] can be now assigned to variables, as [[Java_Language#Values|values]], and passed around, which essentially means passing code around. Functions come in form of [[#Lambda_Expression|lambda expressions]] (anonymous functions) or [[#Method_Reference|method references]].


=Lambda Expression=
=Lambda Expression=
Line 16: Line 18:
A lambda expression is a representation of an ''anonymous [[Functional_Programming#Function|function]]'': it does not have a name, but it has a list of parameters, a body, a return type, and possibly a list of exceptions that can be thrown.
A lambda expression is a representation of an ''anonymous [[Functional_Programming#Function|function]]'': it does not have a name, but it has a list of parameters, a body, a return type, and possibly a list of exceptions that can be thrown.


Lambda expressions can be stored as [[Java_Language#Values|values]], in [[Java_Language#Variables|variables]], and passed as arguments to methods and constructors. In all these cases, the [[Java_Language#Types|type]] of the lambda value is a [[#Functional_Interface|functional interface]].
Lambda expressions can be stored as [[Java_Language#Values|values]], in [[Java_Language#Variables|variables]], and passed as arguments to methods and constructors. In all these cases, the [[Java_Language#Types|type]] of the lambda value is a [[#Functional_Interface|functional interface]]. Lambda expressions let you provide the implementation of the abstract method of the [[#Functional_Interface|functional interface]] directly in-line and threat the whole expression as an instance of a concrete implementation of the functional interface. Lambda expression values can be assigned to variables or passed to methods everywhere the corresponding functional interface argument is expected. The compiler will insure the lambda implementation [[#Lambdas_and_Compile-Time_Type_Checking|matches the type]].
 
Unlike Scala, which has a function type, Java reuses existing nominal types provided by the [[#Functional_Interface|functional interfaces]] and maps them to a form of functional types behind the scenes.


Semantically, lambda expressions do not allow programmers to do anything that couldn't have been done before their introduction in Java 8, via anonymous classes. However, the lambda syntax is more concise, lambda expressions are a convenient way of increasing the code clarity by in-lining logic. If the lambda's body exceeds a few lines in length, so that its behavior isn't instantly clear, the logic should be encapsulated in a method and a  [[#Method_Reference|method reference]] should be used instead of the lambda expression.
Semantically, lambda expressions do not allow programmers to do anything that couldn't have been done before their introduction in Java 8, via anonymous classes. However, the lambda syntax is more concise, lambda expressions are a convenient way of increasing the code clarity by in-lining logic. If the lambda's body exceeds a few lines in length, so that its behavior isn't instantly clear, the logic should be encapsulated in a method and a  [[#Method_Reference|method reference]] should be used instead of the lambda expression.
Line 22: Line 26:
The term ''lambda'' comes from a system developed in academia called [https://en.wikipedia.org/wiki/Lambda_calculus lambda calculus], which is used to describe computations.
The term ''lambda'' comes from a system developed in academia called [https://en.wikipedia.org/wiki/Lambda_calculus lambda calculus], which is used to describe computations.


==Syntax==
=Lambda Expression Syntax=


A lambda expression declaration consists in a [[#Formal_Parameters|comma-separated list of formal parameters]], enclosed in parentheses, followed by the "arrow" token, followed by a [[#The_Body|body]].
A lambda expression declaration consists in a [[#Formal_Parameters|comma-separated list of formal parameters]], enclosed in parentheses, followed by the "arrow" token, followed by a [[#The_Body|body]].
Line 28: Line 32:
  (''comma-separated-parameter-list'') -> ''body''
  (''comma-separated-parameter-list'') -> ''body''


===Formal Parameters===
==Formal Parameters==


The most generic format of the ''parameter-list'' is:
The most generic format of the ''parameter-list'' is:
Line 34: Line 38:
  ([''Type1''] ''var1'', [''Type2''] ''var2'', ...)
  ([''Type1''] ''var1'', [''Type2''] ''var2'', ...)


The type of parameters may be omitted, thanks to the [[Java_7_Type_Inference|type inference mechanism]].
The type of parameters may be omitted, thanks to the [[#Lambda_Parameters_Type_Inference|type inference mechanism]].
 
If and only if there is a single parameter, the enclosing parentheses may be omitted, along with the type specification. Note that omitting only the parentheses, but not the type specification is considered a syntax error, both must be omitted at the same time. Example:


<syntaxhighlight lang='java'>
a -> ...
</syntaxhighlight>


Note that sometimes the code is more readable if we include the types explicitly and sometimes more readable if we exclude them.


The parameter list could be empty:
The parameter list could be empty, but in this case the parentheses are required:


<syntaxhighlight lang='java'>
  () -> ...
  () -> ...
</syntaxhighlight>


"->" is referred to as "arrow".
"->" is referred to as "arrow".


===The Body===
==The Body==


The ''body'' can be a single [[Java_Language#Expressions|expression]], and it this case the lambda is known as an "[[#Expression-Style_Lambda|expression-style lambda]]", or a list of [[Java_Language#Statements|statements]] included enclosed in curly braces - a block - and in this case the lambda is known as "[[#Block-Style_Lambda|block-style lambda]]".
The ''body'' can be a single [[Java_Language#Expressions|expression]], and it this case the lambda is known as an "[[#Expression-Style_Lambda|expression-style lambda]]", or a list of [[Java_Language#Statements|statements]] included enclosed in curly braces - a block - and in this case the lambda is known as "[[#Block-Style_Lambda|block-style lambda]]".


====Block-Style Lambda====
===Block-Style Lambda===


  (''parameter-list'') -> { ''statement1''; ''statement2''; ... }
  (''parameter-list'') -> { ''statement1''; ''statement2''; ... }
Line 67: Line 79:
</syntaxhighlight>
</syntaxhighlight>


If the lambda execution returns a value, the last statement in the block must be <tt>return</tt>:
If the lambda returns a value, the last statement in the block must be <tt>return</tt>:


<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
Line 76: Line 88:
</syntaxhighlight>
</syntaxhighlight>


====Expression-Style Lambda====
If the lambda returns void, and the body consists in a single statement that also returns void, the curly braces around the body may be omitted:
 
<syntaxhighlight lang='java'>
(...) -> System.out.println("something");
</syntaxhighlight>
 
====Special Void-Compatibility Rule====
 
A lambda that returns void may accept a statement whose return is non-void. In this case the return is discarded.
 
<syntaxhighlight lang='java'>
@FunctionalInterface
public interface FunctionalInterfaceWhoseMethodReturnsVoid {
 
    void update(String s);
 
}
 
final List<String> shared = new ArrayList<>();
 
FunctionalInterfaceWhoseMethodReturnsVoid l = s -> shared.add(s);
 
</syntaxhighlight>
 
Note that shared.add(s) returns a boolean, while update() returns void. The return value of the shared.add(s) statement is discarded.
 
===Expression-Style Lambda===


  (''parameter-list'') -> ''expression''
  (''parameter-list'') -> ''expression''
Line 91: Line 129:
=Functional Interface=
=Functional Interface=


A lambda value ''type'' is given by a functional interface: lambda values can be used and passed around everywhere a functional interface is expected.
A lambda value '''type''' is specified by a '''functional interface''': lambda values can be used and passed around everywhere a functional interface is expected.
 
A '''functional interface''' is a [[Java_Language#Interface|Java interface]] that ''specifies exactly one abstract method''. Note that an interface that has exactly one abstract method and several [[Java_8_Default_Methods_in_Interfaces|default methods]] is still a valid functional interface. In different words, an interface is still a functional interface if it has default methods, as long as it specifies only one abstract method.
 
We call the abstract method of a functional interface the '''[[#Function_Descriptor|function descriptor]]'''.
 
==Function Descriptor==
 
The '''function descriptor''' is the only one abstract method of a [[#Functional_Interface|functional interface]]. The function descriptor may also be referred to as '''functional method'''.
 
The function descriptor's method signature - the parameter list, the return type and possibly the exceptions thrown - must match the signature of the lambda expression. The name of the abstract method is irrelevant, all that matters are the parameters, the return type and the thrown exceptions, if any.
 
Sometimes, the following notation is uses to express the function descriptor:
 
(''parameter-type-list'') -> ''return-type''


A ''functional interface'' is a [[Java_Language#Interface|Java interface]] that ''specifies exactly one abstract method''. Note that an interface that has exactly one abstract method and several default methods is still a valid functional interface.
Example:


The functional interface's abstract method signature - the parameter list, the return type and possibly the exceptions thrown - must match the lambda expression signature.
<syntaxhighlight lang='java'>
() -> void
(Apple, Apple) -> int
</syntaxhighlight>


==@FunctionalInterface==
==@FunctionalInterface==


Library interfaces annotated with @FunctionalInterface:
This annotation is used to indicate that an interface is intended to be used as a functional interface, and is therefore useful for documentation. The compiler will return an error if you annotate with @FunctionalInterface an interface that isn't a functional interface. The @FunctionalInterface annotation is ''not'' mandatory, but it is a good practice to use it when an interface is designed with this purpose. In this respect, is similar to the @Override annotation.


* <tt>java.lang.Runnable</tt> https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html
==Library @FunctionalIntefaces==
* <tt>[[Java.util.concurrent#Callable|java.util.concurrent.Callable]]</tt>
* <tt>java.util.Comparator</tt> https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
* <tt>java.util.function.Predicate</tt> https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html


* [https://github.com/NovaOrdis/playground/blob/master/java/java8/lambda-expressions/03-other-standard-functional-interfaces/src/main/java/io/novaordis/playground/java/java8/lambda/Main.java GitHub Examples]
Java 8 comes with a set of pre-defined functional interfaces that describe common [[#Function_Descriptor|function descriptors]]. Those interfaces are annotated with @FunctionalInterface. More details on "java.util.function" interfaces: {{External|https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html}}


==Predicate==
====Runnable====


A ''predicate'' is a function that evaluates an argument and returns a boolean.
{{External|https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html}}


{{External|https://github.com/NovaOrdis/playground/tree/master/java/java8/lambda-expressions/02-predicate}}
====Comparable====


=Method Reference=
{{Internal|java.lang.Comparable|<tt>java.lang.Comparable<T></tt>}}
 
====Comparator====
 
{{Internal|Comparator|<tt>java.util.Comparator<T></tt>}}
 
====Callable====
 
{{Internal|Java.util.concurrent#Callable|<tt>java.util.concurrent.Callable<V></tt>}}
 
====<span id='Predicate'></span>Predicate, IntPredicate, LongPredicate, DoublePredicate====
 
{{Internal|Predicate|<tt>java.util.function.Predicate<T></tt>}}
 
====BiPredicate====
 
{{External|https://docs.oracle.com/javase/8/docs/api/java/util/function/BiPredicate.html}}
 
====<span id='Function'></span>Function, IntFunction, ToIntFunction====
 
Select/extract from an object.
 
{{Internal|java.util.function.Function|<tt>java.util.function.Function<T, R></tt>}}
 
====BiFunction====
 
{{Internal|java.util.function.BiFunction#Overview|<tt>java.util.function.BiFunction<T, U, R></tt>}}
 
====Consumer====
{{External|https://docs.oracle.com/javase/10/docs/api/java/util/function/Consumer.html}}
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, <code>Consumer</code> is expected to operate via side-effects.
<syntaxhighlight lang='java'>
@FunctionalInterface
public interface Consumer<T> {
    void accept​(T t);
}
</syntaxhighlight>
 
====BiConsumer====
{{External|https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html}}
Represents an operation that accepts to input arguments and returns no result. Unlike most other functional interfaces, BiConsumer is expected to operate via side-effects.
<syntaxhighlight lang='java'>
@FunctionalInterface
public interface BiConsumer<T, U> {
  void accept(T t, U u);
}
</syntaxhighlight>
A <code>Map.forEach()</code> expects a <code>BiConsumer</code> instance to which it will pass, in order, the key and the value.
 
====Supplier====
 
{{Internal|java.util.function.Supplier|<tt>java.util.function.Supplier<T></tt>}}
 
====UnaryOperator====
 
{{Internal|java.util.function.UnaryOperator|<tt>java.util.function.UnaryOperator<T></tt>}}
 
====BinaryOperator====
 
Combine two values.


The semantics behind the method reference syntax is ''use this method as a value''.
{{Internal|java.util.function.BinaryOperator|<tt>java.util.function.BinaryOperator<T></tt>}}


The <''Class-Name''>::<''method-name''> syntax creates a method reference, which then can be passed around as a [[Java_Language#Value|value]].
=Lambdas and Exceptions=


=Relationship between Lambda Expressions and Method References=
<syntaxhighlight lang='java'>
@FunctionalInterface
public interface ExceptionLambda {


    String process(String s) throws Exception;
}


...


ExceptionLambda el = s -> {


  if ("something".equals(s)) {
      throw new Exception("something");
  }


  return s.toUpperCase();
}
</syntaxhighlight>


If you use a standard functional interface whose signature does not allow exceptions, the lambda implementation will need to catch whatever exceptions are thrown by its statements and wrap them in RuntimeExceptions.


=Lambdas and Compile-Time Type Checking=


Lambda instances can be assigned to functional interface-typed variables. However, the lambda implementation does not contain any information on the functional interface it is specifically implementing - if any.


The type of a lambda is deduced from the context into which the lambda is used: assignment, method invocation (parameters and return) or cast. The type thus determined is called the [[Java_7_Type_Inference#Target_Type|target type]]. The compiler performs a compatibility check, making sure that the signature of the target type's [[#Function_Descriptor|function descriptor]] is identical with the the lambda's signature.


Because all that needs to match is the signature of the lambda, the same lambda expression can be associated with different functional interfaces, as long as they have the same [[#Function_Descriptor|function descriptor]] signature.


=Lambda Parameters Type Inference=


The compiler deduces the target type from context, so it knows the type of the parameters - they are specified in the functional interface definition. Thus, it is not necessary to specify the type of the parameters in the lambda expression declaration: if the types are specified, they are tolerated, but they are not required.


The following declarations are equivalent:


<syntaxhighlight lang='java'>
SomeFunctionalInterface l = (String s, Integer i) -> s + " " + i.toString();
</syntaxhighlight>


-----------------
<syntaxhighlight lang='java'>
SomeFunctionalInterface l = (s, i) -> s + " " + i.toString();
</syntaxhighlight>


=To Process=
Note that in the second case, the parameters' types are not specified. They are known to the compiler from the definition of the target type SomeFunctionalInterface.


=Syntax=
=Variable Capture=


A lambda expression consists in a ''comma-separated list of formal parameters, enclosed in parentheses'', followed by the arrow token "->" followed by a ''body'', which may be a single expression or a statement block.
Lambda expressions are allowed to use the variables present in the scope in which the lambda is declared. For this reason, they are called ''capturing lambdas''. However, different types of variable behave differently:


<pre>
[[Java_Language#Class_Variable|Class]] and [[Java_Language#Instance_Variable|instance]] variables can be used without any special concern. Capturing an instance variable can be seen as capturing the final local variable <tt>this</tt>. Class and instance variables are accessible from the lambda code, and they can be modified by the lambda - subject to safe concurrent access rules. Note that according to the functional programming philosophy, lambdas should not mutate external state, as a side-effect.
(comma_separated_formal_parameter_list) -> body
</pre>


==Formal Parameters==
[[Java_Language#Local_Variable|Local]] variables have to be explicitly declared <tt>final</tt> or be [[Java_Language#Java_8_Effectively_Final_Variable|effectively final]]. Local variables are allocated on a thread's stack, and they are deallocated when the thread stack unwinds. If a lambda accessed a non-final local variable, and was executed from another thread - which is common for lambdas - it could get into the situation where it accesses a deallocated variable, which would cause a runtime error. To protect against this situation, the local variables captured by lambdas  have to be explicitly declared final, or be effectively final, so the content of the variable is copied in the lambda block. This way, the lambda will always access a copy of a local variable, and not the original variable.


The type of the parameters may be omitted.
From this perspective, lambdas are not [[Closures#Overview|closures]]. Closures can refer variables - including variables local to the scope the closure was defined in - with no restriction. Lambdas close over ''values'', not ''variables''.


If there is a single parameter, the enclosed parentheses may be omitted.
=Method Reference=


==Body==
A lambda expression can be replaced with a ''method reference'' if its body consists of ''only one method invocation'', in one of the cases described below:
# [[#Lambda_Expression_Body_Consists_of_a_Class_Method_Invocation|Lambda expression body consists of a class method invocation]]
# [[#Lambda_Expression_Body_Consists_of_an_Instance_Method_Invocation_on_the_First_Lambda_Argument|Lambda expression body consists of an instance method invocation on the first lambda argument]]
# [[#Lambda_Expression_Body_Consists_of_an_Instance_Method_Invocation_on_an_External_Expression|Lambda expression body consists of an instance method invocation on an external expression]]
# [[#Constructor_Method_Reference|Constructor method reference]]
# [[#Array_Constructor_Method_Reference|Array constructor method reference]]
# [[#Super-Call_Method_Reference|Super-call method reference]]


The body may be a single expression, or a statement block.
A ''method reference'' is a syntactically friendly way of referring to the code of a method by the method name, and use this name as a lambda expression. The idea is that if a lambda represents "call just this one method directly", then it is best to refer to the method by name, rather than a description of how to call it. Presumably, this improves code readability. When specifying a method reference, no brackets are needed because specifying the method reference is not actually calling the method, but passing code around.


=Referencing a Lambda Expression=
The compiler goes through a similar type checking process for method references as for [[#Lambdas_and_Compile-Time_Type_Checking|lambdas]]: the signature of the method reference has to match the target type inferred from the context.


==Lambda Expression Body Consists of a Class Method Invocation==


=Method References=
If the lambda's body consists in a single static method invocation, the lambda can be replaced with the static method's reference as follows:


(args) -> '''ClassName'''.<font color=olive>staticMethod</font>(args)


<font color=red>
is equivalent with:
 
'''ClassName'''::<font color=olive>staticMethod</font>


Example:
Example:


<pre>
(String s) -> Integer.<font color=olive>parseInt</font>(s)
    public ZipHandler getZipHandler() {


        return ZipUtil::getTopLevelDirectoryName;
is equivalent with:
    }
Integer::<font color=olive>parseInt</font>


</pre>
==Lambda Expression Body Consists of an Instance Method Invocation on the First Lambda Argument==


</font>
('''arg0''', rest) -> '''arg0'''.<font color=olive>instanceMethod</font>(rest)


=Variables=
is equivalent with:


The variables used in the lambda expressions must be final.
'''arg0-ClassName'''::<font color=olive>instanceMethod</font>


where <tt>arg0</tt> is of type ClassName and <tt>rest</tt> may contain zero or more arguments.


=TODO=
Single-argument instance method reference example:
 
('''Apple''' '''a''') -> '''a'''.<font color=olive>getWeight</font>()
 
is equivalent with:
 
'''Apple'''::<font color=olive>getWeight</font>
 
Two-argument instance method reference example:
 
('''String''' '''s''', int i) -> '''s'''.<font color=olive>substring</font>(i)
 
is equivalent with:
'''String'''::<font color=olive>substring</font>
 
==Lambda Expression Body Consists of an Instance Method Invocation on an External Expression==
 
This case refers to calling the method in the lambda onto an external object that already exists:
 
(args) -> '''expr'''.<font color=olive>instanceMethod</font>(args)
 
is equivalent with:
'''expr'''::<font color=olive>instanceMethod</font>
 
No-argument example:
 
() -> '''Thread.currentThread()'''.<font color=olive>dumpStack</font>()
 
is equivalent with:
 
'''Thread.currentThread()'''::<font color=olive>dumpStack</font>
 
Single-argument example:
 
(String s) -> '''System.out'''.<font color=olive>println</font>(s)
 
is equivalent with:
 
'''System.out'''::<font color=olive>println</font>
 
==Constructor Method Reference==
 
'''ClassName'''::<font color=olive>new</font>
 
==Array Constructor Method Reference==
 
==Super-Call Method Reference==


<font color=red>
=Lambda Composition=


* Lambda Expressions Tutorial https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Some of the functional interfaces provide methods that allow ''composition'': combination of several simple lambda expressions to build more complicated ones.
* java.util.function https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html


</font>
* [[Comparator#Composition_Methods|Comparator composition methods]]
* [[Predicate#Composition_Methods|Predicate composition methods]]
* [[Java.util.function.Function#Composition_Methods|Function composition methods]]

Latest revision as of 01:05, 17 September 2021

External

Internal

TODO

Overview

Java 8 introduces functional programming features, in the form of lambda expressions. Lambda expressions allow behavior parameterization - functions can be now assigned to variables, as values, and passed around, which essentially means passing code around. Functions come in form of lambda expressions (anonymous functions) or method references.

Lambda Expression

A lambda expression is a representation of an anonymous function: it does not have a name, but it has a list of parameters, a body, a return type, and possibly a list of exceptions that can be thrown.

Lambda expressions can be stored as values, in variables, and passed as arguments to methods and constructors. In all these cases, the type of the lambda value is a functional interface. Lambda expressions let you provide the implementation of the abstract method of the functional interface directly in-line and threat the whole expression as an instance of a concrete implementation of the functional interface. Lambda expression values can be assigned to variables or passed to methods everywhere the corresponding functional interface argument is expected. The compiler will insure the lambda implementation matches the type.

Unlike Scala, which has a function type, Java reuses existing nominal types provided by the functional interfaces and maps them to a form of functional types behind the scenes.

Semantically, lambda expressions do not allow programmers to do anything that couldn't have been done before their introduction in Java 8, via anonymous classes. However, the lambda syntax is more concise, lambda expressions are a convenient way of increasing the code clarity by in-lining logic. If the lambda's body exceeds a few lines in length, so that its behavior isn't instantly clear, the logic should be encapsulated in a method and a method reference should be used instead of the lambda expression.

The term lambda comes from a system developed in academia called lambda calculus, which is used to describe computations.

Lambda Expression Syntax

A lambda expression declaration consists in a comma-separated list of formal parameters, enclosed in parentheses, followed by the "arrow" token, followed by a body.

(comma-separated-parameter-list) -> body

Formal Parameters

The most generic format of the parameter-list is:

([Type1] var1, [Type2] var2, ...)

The type of parameters may be omitted, thanks to the type inference mechanism.

If and only if there is a single parameter, the enclosing parentheses may be omitted, along with the type specification. Note that omitting only the parentheses, but not the type specification is considered a syntax error, both must be omitted at the same time. Example:

a -> ...

Note that sometimes the code is more readable if we include the types explicitly and sometimes more readable if we exclude them.

The parameter list could be empty, but in this case the parentheses are required:

 () -> ...

"->" is referred to as "arrow".

The Body

The body can be a single expression, and it this case the lambda is known as an "expression-style lambda", or a list of statements included enclosed in curly braces - a block - and in this case the lambda is known as "block-style lambda".

Block-Style Lambda

(parameter-list) -> { statement1; statement2; ... }

The absence of a return as the last statement in the block implies that the lambda returns void:

(Apple a) -> { 
    System.out.println("the apple is " + a.getColor());
    System.out.println("the apple weighs " + a.getWeight() + " grams");
};

This lambda, that has no parameters and returns void, is valid:

() -> {}

If the lambda returns a value, the last statement in the block must be return:

(Apple a) -> { 
    boolean heavy = a.getWeight() > 100; 
    return a.getColor() + "(" + (heavy ? "heavy":"light") + ")"; 
};

If the lambda returns void, and the body consists in a single statement that also returns void, the curly braces around the body may be omitted:

(...) -> System.out.println("something");

Special Void-Compatibility Rule

A lambda that returns void may accept a statement whose return is non-void. In this case the return is discarded.

@FunctionalInterface
public interface FunctionalInterfaceWhoseMethodReturnsVoid {

    void update(String s);

}

final List<String> shared = new ArrayList<>();

FunctionalInterfaceWhoseMethodReturnsVoid l = s -> shared.add(s);

Note that shared.add(s) returns a boolean, while update() returns void. The return value of the shared.add(s) statement is discarded.

Expression-Style Lambda

(parameter-list) -> expression

If the lambda is supposed to return a value, then the value the expression evaluates to is returned as value of lambda execution.

(Apple a) -> a.getColor() + " (" + a.getWeight() + " grams)";

If the lambda is supposed to return void, the value the expression evaluates to is discarded.

Functional Interface

A lambda value type is specified by a functional interface: lambda values can be used and passed around everywhere a functional interface is expected.

A functional interface is a Java interface that specifies exactly one abstract method. Note that an interface that has exactly one abstract method and several default methods is still a valid functional interface. In different words, an interface is still a functional interface if it has default methods, as long as it specifies only one abstract method.

We call the abstract method of a functional interface the function descriptor.

Function Descriptor

The function descriptor is the only one abstract method of a functional interface. The function descriptor may also be referred to as functional method.

The function descriptor's method signature - the parameter list, the return type and possibly the exceptions thrown - must match the signature of the lambda expression. The name of the abstract method is irrelevant, all that matters are the parameters, the return type and the thrown exceptions, if any.

Sometimes, the following notation is uses to express the function descriptor:

(parameter-type-list) -> return-type

Example:

() -> void
(Apple, Apple) -> int

@FunctionalInterface

This annotation is used to indicate that an interface is intended to be used as a functional interface, and is therefore useful for documentation. The compiler will return an error if you annotate with @FunctionalInterface an interface that isn't a functional interface. The @FunctionalInterface annotation is not mandatory, but it is a good practice to use it when an interface is designed with this purpose. In this respect, is similar to the @Override annotation.

Library @FunctionalIntefaces

Java 8 comes with a set of pre-defined functional interfaces that describe common function descriptors. Those interfaces are annotated with @FunctionalInterface. More details on "java.util.function" interfaces:

https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

Runnable

https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html

Comparable

java.lang.Comparable<T>

Comparator

java.util.Comparator<T>

Callable

java.util.concurrent.Callable<V>

Predicate, IntPredicate, LongPredicate, DoublePredicate

java.util.function.Predicate<T>

BiPredicate

https://docs.oracle.com/javase/8/docs/api/java/util/function/BiPredicate.html

Function, IntFunction, ToIntFunction

Select/extract from an object.

java.util.function.Function<T, R>

BiFunction

java.util.function.BiFunction<T, U, R>

Consumer

https://docs.oracle.com/javase/10/docs/api/java/util/function/Consumer.html

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

BiConsumer

https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html

Represents an operation that accepts to input arguments and returns no result. Unlike most other functional interfaces, BiConsumer is expected to operate via side-effects.

@FunctionalInterface
public interface BiConsumer<T, U> {
  void accept(T t, U u);
}

A Map.forEach() expects a BiConsumer instance to which it will pass, in order, the key and the value.

Supplier

java.util.function.Supplier<T>

UnaryOperator

java.util.function.UnaryOperator<T>

BinaryOperator

Combine two values.

java.util.function.BinaryOperator<T>

Lambdas and Exceptions

@FunctionalInterface
public interface ExceptionLambda {

    String process(String s) throws Exception;
}

...

ExceptionLambda el = s -> {

  if ("something".equals(s)) {
      throw new Exception("something");
  }

  return s.toUpperCase();
}

If you use a standard functional interface whose signature does not allow exceptions, the lambda implementation will need to catch whatever exceptions are thrown by its statements and wrap them in RuntimeExceptions.

Lambdas and Compile-Time Type Checking

Lambda instances can be assigned to functional interface-typed variables. However, the lambda implementation does not contain any information on the functional interface it is specifically implementing - if any.

The type of a lambda is deduced from the context into which the lambda is used: assignment, method invocation (parameters and return) or cast. The type thus determined is called the target type. The compiler performs a compatibility check, making sure that the signature of the target type's function descriptor is identical with the the lambda's signature.

Because all that needs to match is the signature of the lambda, the same lambda expression can be associated with different functional interfaces, as long as they have the same function descriptor signature.

Lambda Parameters Type Inference

The compiler deduces the target type from context, so it knows the type of the parameters - they are specified in the functional interface definition. Thus, it is not necessary to specify the type of the parameters in the lambda expression declaration: if the types are specified, they are tolerated, but they are not required.

The following declarations are equivalent:

SomeFunctionalInterface l = (String s, Integer i) -> s + " " + i.toString();
SomeFunctionalInterface l = (s, i) -> s + " " + i.toString();

Note that in the second case, the parameters' types are not specified. They are known to the compiler from the definition of the target type SomeFunctionalInterface.

Variable Capture

Lambda expressions are allowed to use the variables present in the scope in which the lambda is declared. For this reason, they are called capturing lambdas. However, different types of variable behave differently:

Class and instance variables can be used without any special concern. Capturing an instance variable can be seen as capturing the final local variable this. Class and instance variables are accessible from the lambda code, and they can be modified by the lambda - subject to safe concurrent access rules. Note that according to the functional programming philosophy, lambdas should not mutate external state, as a side-effect.

Local variables have to be explicitly declared final or be effectively final. Local variables are allocated on a thread's stack, and they are deallocated when the thread stack unwinds. If a lambda accessed a non-final local variable, and was executed from another thread - which is common for lambdas - it could get into the situation where it accesses a deallocated variable, which would cause a runtime error. To protect against this situation, the local variables captured by lambdas have to be explicitly declared final, or be effectively final, so the content of the variable is copied in the lambda block. This way, the lambda will always access a copy of a local variable, and not the original variable.

From this perspective, lambdas are not closures. Closures can refer variables - including variables local to the scope the closure was defined in - with no restriction. Lambdas close over values, not variables.

Method Reference

A lambda expression can be replaced with a method reference if its body consists of only one method invocation, in one of the cases described below:

  1. Lambda expression body consists of a class method invocation
  2. Lambda expression body consists of an instance method invocation on the first lambda argument
  3. Lambda expression body consists of an instance method invocation on an external expression
  4. Constructor method reference
  5. Array constructor method reference
  6. Super-call method reference

A method reference is a syntactically friendly way of referring to the code of a method by the method name, and use this name as a lambda expression. The idea is that if a lambda represents "call just this one method directly", then it is best to refer to the method by name, rather than a description of how to call it. Presumably, this improves code readability. When specifying a method reference, no brackets are needed because specifying the method reference is not actually calling the method, but passing code around.

The compiler goes through a similar type checking process for method references as for lambdas: the signature of the method reference has to match the target type inferred from the context.

Lambda Expression Body Consists of a Class Method Invocation

If the lambda's body consists in a single static method invocation, the lambda can be replaced with the static method's reference as follows:

(args) -> ClassName.staticMethod(args)

is equivalent with:

ClassName::staticMethod

Example:

(String s) -> Integer.parseInt(s)

is equivalent with:

Integer::parseInt

Lambda Expression Body Consists of an Instance Method Invocation on the First Lambda Argument

(arg0, rest) -> arg0.instanceMethod(rest)

is equivalent with:

arg0-ClassName::instanceMethod

where arg0 is of type ClassName and rest may contain zero or more arguments.

Single-argument instance method reference example:

(Apple a) -> a.getWeight()

is equivalent with:

Apple::getWeight

Two-argument instance method reference example:

(String s, int i) -> s.substring(i)

is equivalent with:

String::substring

Lambda Expression Body Consists of an Instance Method Invocation on an External Expression

This case refers to calling the method in the lambda onto an external object that already exists:

(args) -> expr.instanceMethod(args)

is equivalent with:

expr::instanceMethod

No-argument example:

() -> Thread.currentThread().dumpStack()

is equivalent with:

Thread.currentThread()::dumpStack

Single-argument example:

(String s) -> System.out.println(s)

is equivalent with:

System.out::println

Constructor Method Reference

ClassName::new

Array Constructor Method Reference

Super-Call Method Reference

Lambda Composition

Some of the functional interfaces provide methods that allow composition: combination of several simple lambda expressions to build more complicated ones.