EN
Java 8 - difference between lambda expression and method reference
0
points
In this article, we would like to show you the differences between lambda expression and method reference in Java 8.
1. Overview
In this section, we list a few general differences.
Lambda expression:
- an anonymous method (it doesn't have a name),
- is used to provide the inline implementation of a method defined by the functional interface,
- the arrow operator (
->
) connects the argument and functionality, - long lambda expressions consisting of many statements may reduce the readability of the code.
Method reference:
- re-usable (no need to copy and paste lambda expression),
- refers to a method without executing it,
- the double colon operator (
::
) separates the method name from the name of an object or class, - extracting many statements from lambda expression in a method and referencing it may improve the readability of the code,
2. Syntax
Lambda Expression | Method Reference |
---|---|
One parameter:
Multiple parameters:
For more complex operations:
|
Reference to a static method:
Reference to an instance method of a particular object:
Reference to an instance method of an arbitrary object of a particular type:
Reference to a constructor:
|
Practical example
In this example, we use both lambda expression and method reference to achieve the same effect - print list
items in lowercase.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
// Using lambda expression to print list items in lower case
System.out.println("----- Lambda expression -----");
list.stream().map(x -> x.toLowerCase())
.forEach(x -> System.out.println(x));
// Using method reference to print list items in lower case
System.out.println("----- Method reference -----");
list.stream().map(String::toLowerCase).sorted()
.forEach(System.out::println);
}
}
Output:
----- Lambda expression -----
a
b
c
----- Method reference -----
a
b
c