Java 8 Lambda Expressions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 15: Line 15:


An ''anonymous function''.
An ''anonymous function''.
==Statement Lambda==
<syntaxhighlight lang='java'>
</syntaxhighlight>
==Expression Lambda==
<syntaxhighlight lang='java'>
</syntaxhighlight>


=Method Reference=
=Method Reference=

Revision as of 21:10, 22 March 2018

External

Internal

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 lambdas (anonymous functions) or method references.

Lambda

An anonymous function.

Statement Lambda

Expression Lambda

Method Reference

The semantics behind the method reference syntax is use this method as a value.

The <Class-Name>::<method-name> syntax creates a method reference, which then can be passed around as a value.



To Process

A lambda expression can be thought of as an anonymous methods. As shown in the "Syntax" section below, a lambda expression looks a lot like a method declaration.

TODO: one pass yellow/de-yellow over the Oracle tutorial.

Playground Example

https://github.com/NovaOrdis/playground/blob/master/java/java8/lambda-expression/src/main/java/io/novaordis/playground/java/java8/lambda/Main.java

Functional Interface

An interface with only one method is named functional interface

Apparently this is the type of a lambda expression, it describe the function signature.

The Type of a Lambda Expression

Elaborate here.

Syntax

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.

(comma_separated_formal_parameter_list) -> body

Formal Parameters

The type of the parameters may be omitted.

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

Body

The body may be a single expression, or a statement block.

Referencing a Lambda Expression

Method References

Example:

    public ZipHandler getZipHandler() {

        return ZipUtil::getTopLevelDirectoryName;
    }

Variables

The variables used in the lambda expressions must be final.


Statement Lambdas and Expression Lambdas

Statement Lambda:

(ZipEntry e) -> {  s.append(e.getName()); }

Expression Lambda:

(ZipEntry e) -> s.append(e.getName())


TODO