To learn more about anonymous functions, please visit
Lambda expressions, also called closures, are the most important new feature driving the release of Java 8.
Lambda allows a function to be treated as a method parameter (functions passed as parameters into methods).
Using lambda expressions can make code more concise and compact.
Syntax
The syntax of lambda expressions is as follows:
(
parameters
)
->
expression
or
(
parameters
)
->
{
statements
;
}
parameters is the parameter list,expression or { statements; } is the body of the lambda expression. If there is only one parameter, the parentheses can be omitted; if there are no parameters, empty parentheses are still required.
Below is a simple example demonstrating the use of a lambda expression to compute the sum of two numbers:
Example
// Use a lambda expression to compute the sum of two numbers
MathOperation addition
=
(
a, b
)
->
a
b
;
// Call the lambda expression
int
result
=
addition.
operation
(
5
,
3
)
;
System
.
out
.
println
(
"5 + 3 = "
result
)
;
In the above example, MathOperation is a functional interface containing an abstract method operation; the lambda expression (a, b) -> a + b implements this abstract method, representing the addition of the two parameters.
Lambda expressions can be used in various scenarios, including collection operations, event handling, etc. Below is an example of using a lambda expression to traverse a list:
Example
List
<
String
names
=
Arrays
.
asList
(
"Alice"
,
"Bob"
,
"Charlie"
)
;
// Use a lambda expression to traverse the list
names.
forEach
(
name
->
System
.
out
.
println
(
name
)
)
;
Lambda expressions introduce a more functional programming style in Java, making code more concise and readable; it is an important improvement to functional programming in Java 8.
Important Features
simplicity
Lambda expressions provide a more concise syntax, especially suitable for functional interfaces. Compared with traditional anonymous inner classes, lambda expressions make code more compact and reduce boilerplate code.
Example
// Traditional anonymous inner class
Runnable
runnable1
=
new
Runnable
(
)
{
@Override
public
void
run
(
)
{
System
.
out
.
println
(
"Hello World!"
)
;
}
}
;
// Using a lambda expression
Runnable
runnable2
=
(
)
->
System
.
out
.
println
(
"Hello World!"
)
;
Functional Programming Support
Lambda expressions are an embodiment of functional programming; they allow functions to be passed as parameters to methods or returned as values. This support makes Java more flexible in functional programming and better able to handle tasks such as collection operations and parallel computing.
Example
// Pass a lambda expression as a parameter to a method
List
<
String
names
=
Arrays
.
asList
(
"Alice"
,
"Bob"
,
"Charlie"
)
;
names.
forEach
(
name
->
System
.
out
.
println
(
name
)
)
;
Variable Capture
Lambda expressions can access variables from the outer scope; this characteristic is called variable capture. Lambda expressions can implicitly capture final or effectively final local variables.
Example
// Variable capture
int
x
=
10
;
MyFunction myFunction
=
y
->
System
.
out
.
println
(
x
y
)
;
myFunction.
doSomething
(
5
)
;
// Output 15
Method References
Lambda expressions can be further simplified through method references; method references allow you to directly reference methods of existing classes or objects without writing redundant code.
Example
// Use a method reference
List
<
String
names
=
Arrays
.
asList
(
"Alice"
,
"Bob"
,
"Charlie"
)
;
names.
forEach
(
System
.
out
::
println
)
;
Parallelism
Lambda expressions make parallel operations more convenient; by using the Stream API together with lambda expressions, parallel computing can be implemented more easily, improving program performance.
Example
// Use lambda expressions and the Stream API for parallel computing
List
<
Integer
numbers
=
Arrays
.
asList
(
1
,
2
,
3
,
4
,
5
)
;
int
sum
=
numbers.
parallelStream
(
)
.
mapToInt
(
Integer
::
intValue
)
.
sum
(
)
;
The introduction of lambda expressions makes Java programming more flexible and concise and drives the development of functional programming.
Lambda Expression Example
A simple example of a lambda expression:
// 1. 不需要参数,返回值为 5
() -> 5
// 2. Receive a parameter (number type), return its double value
x -> 2 * x
// 3. Accepts 2 parameters (numbers), and returns their difference
(x, y) -> x – y
// 4. Receive two integers and return their sum
(int x, int y) -> x + y
// 5. Accepts a string object and prints it to the console, returning no value (looks like void)
(String s) -> System.out.print(s)
Enter the following code in the Java8Tester.java file:
Java8Tester.java file
public
class
Java8Tester
{
public
static
void
main
(
String
args
[
]
)
{
Java8Tester
tester
=
new
Java8Tester
(
)
;
//
Type declaration
MathOperation
addition
=
(
int
a
,
int
b
)
->
a
b
;
//
Without type declaration
MathOperation
subtraction
=
(
a
,
b
)
->
a
b
;
//
Return statement in braces
MathOperation
multiplication
=
(
int
a
,
int
b
)
->
{
return
a
b
;
}
;
//
No braces and no return statement
MathOperation
division
=
(
int
a
,
int
b
)
->
a
/
b
;
System
.
out
.
println
(
"
10 + 5 =
"
tester
.
operate
(
10
,
5
,
addition
)
)
;
System
.
out
.
println
(
"
10 - 5 =
"
tester
.
operate
(
10
,
5
,
subtraction
)
)
;
System
.
out
.
println
(
"
10 x 5 =
"
tester
.
operate
(
10
,
5
,
multiplication
)
)
;
System
.
out
.
println
(
"
10 / 5 =
"
tester
.
operate
(
10
,
5
,
division
)
)
;
//
Without parentheses
GreetingService
greetService1
=
message
->
System
.
out
.
println
(
"
Hello
"
message
)
;
//
With parentheses
GreetingService
greetService2
=
(
message
)
->
System
.
out
.
println
(
"
Hello
"
message
)
;
greetService1
.
sayMessage
(
"
Runoob
"
)
;
greetService2
.
sayMessage
(
"
"
)
;
}
interface
MathOperation
{
int
operation
(
int
a
,
int
b
)
;
}
interface
GreetingService
{
void
sayMessage
(
String
message
)
;
}
private
int
operate
(
int
a
,
int
b
,
MathOperation
mathOperation
)
{
return
mathOperation
.
operation
(
a
,
b
)
;
}
}
Executing the above script produces the following output:
$ javac Java8Tester.java
$ java Java8Tester
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Runoob
Hello Google
Note the following two points when using lambda expressions:
-
Lambda expressions are mainly used to define inline-executed method-type interfaces (for example, a simple method interface). In the example above, we use various types of lambda expressions to define the MathOperation interface's method, and then define the execution of operation.
-
Lambda expressions eliminate the hassle of using anonymous methods and give Java simple but powerful functional programming capabilities.
Variable scope
A lambda expression can only reference outer local variables marked final; that is, you cannot modify a local variable defined outside the lambda inside it, otherwise a compilation error occurs.
Enter the following code in the Java8Tester.java file:
Java8Tester.java file
public
class
Java8Tester
{
final
static
String
salutation
=
"
Hello!
"
;
public
static
void
main
(
String
args
[
]
)
{
GreetingService
greetService1
=
message
->
System
.
out
.
println
(
salutation
message
)
;
greetService1
.
sayMessage
(
"
Runoob
"
)
;
}
interface
GreetingService
{
void
sayMessage
(
String
message
)
;
}
}
Executing the above script produces the following output:
$ javac Java8Tester.java
$ java Java8Tester
Hello! Runoob
We can also directly access outer local variables in a lambda expression:
Java8Tester.java file
public
class
Java8Tester
{
public
static
void
main
(
String
args
[
]
)
{
final
int
num
=
1
;
Converter
<
Integer
,
String
s
=
(
param
)
->
System
.
out
.
println
(
String
.
valueOf
(
param
num
)
)
;
s
.
convert
(
2
)
;
//
The output is 3
}
public
interface
Converter
<
T1
,
T2
{
void
convert
(
int
i
)
;
}
}
A lambda expression's local variables do not need to be declared final, but they must not be modified by later code (i.e., they implicitly have final semantics)
int num = 1;
Converter s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5;
//Error message: Local variable num defined in an enclosing scope must be final or effectively
final
In a lambda expression, it is not allowed to declare a parameter or local variable with the same name as a local variable.
String first = "";
Comparator comparator = (first, second) -> Integer.compare(first.length(), second.length()); //编译会出错
Java 8 New Features