Chapter 2. Functional Java
Unsurprisingly, lambda expressions are the key to having a functional approach in Java.
In this chapter, you will learn how to use lambdas in Java, why they are so important, how to use them efficiently, and how they work internally.
What Are Java Lambdas?
A lambda expression is a single line or block of Java code that has zero or more parameters and might return a value. From a simplified point of view, a lambda is like an anonymous method that doesn’t belong to any object:
()
->
System
.
out
.
println
(
"Hello, lambda!"
)
Let’s look at the details of the syntax and how lambdas are implemented in Java.
Lambda Syntax
The Java syntax for lambdas is quite similar to the mathematical notation you saw in Chapter 1 for lambda calculus:
(<parameters>) -> { <body> }
The syntax consists of three distinct parts:
- Parameters
-
A comma-separated list of parameters, just like a method argument list. Unlike method arguments, though, you can omit the argument types if the compiler can infer them. Mixing implicitly and explicitly typed parameters is not allowed. You don’t need parentheses for a single parameter, but they are required if none or more than one parameter is present.
- Arrow
-
The
->
(arrow) separates the parameters from the lambda body. It’s the equivalent to in lambda calculus. - Body
-
Either a single expression or a code block. Single-line expressions don’t require curly braces, and their evaluated result returns implicitly without a
return
statement. A ...
Get A Functional Approach to Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.