Lambda Expression as Method Reference
This section describes what is a method reference, which is a shorthand form of a special lambda expression which contains only one static method invocation in the body.
What Is Method Reference?
A method reference is a shorthand form of a special lambda expression which contains only one
static method invocation in the body. Of course, static method parameter list and return should match
the base interface.
Here is the syntax of a method reference:
class_name :: method_name
The above method reference syntax is actually a shorthand form of the following lambda expression syntax:
(parameter_list) -> class_name.method_name(actual_parameter_list)
Comparing the two syntax, I can see that:
- The "parameter_list" is omitted in method reference.
The compiler can get them by looking at the only abstract method of the base interface.
- The "->" is omitted in method reference.
Because the "::" (double colon) token is introduced in method references as identifications of method references.
- The "class_name" and "method_name" are used method reference to identify which method to be invoked.
- The "actual_parameter_list" is omitted in method reference.
The compiler will automatically pass all parameters from the "parameter_list" to the "actual_parameter_list
in the same order.
Here is an example of a method reference:
ClassC :: methodM
The compiler will process the above method reference like the following lambda expression:
(TypeA a, TypeB b) -> ClassC.methodM(a, b)
Of course, we are assuming that the base interface has to following abstract method:
public TypeC c methodI(TypeA a, TypeB b);
See the next section for an example program that uses method references.
Last update: 2014.
Table of Contents
About This Book
Installing JDK 1.8 on Windows
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
Bits, Bytes, Bitwise and Shift Operations
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
StringBuffer - The String Buffer Class
System Properties and Runtime Object Methods
Generic Classes and Parameterized Types
Generic Methods and Type Inference
►Lambda Expressions and Method References
What Is Lambda Expression?
LambdaCalculator.java - Lambda Expression Example
Lambda Expression Syntax Options
►Lambda Expression as Method Reference
Method Reference Example - LambdaMethodRefernce.java
Lambda Expression Stream Pipeline Operations
Execution Threads and Multi-Threading Java Programs
ThreadGroup Class and "system" ThreadGroup Tree
Synchronization Technique and Synchronized Code Blocks
Deadlock Condition Example Programs
Garbage Collection and the gc() Method
PDF Printing Version