I have introduced the method reference in the previous tutorial, in this tutorial, I introduce you another new concept: constructor reference. Like the method reference, the constructor reference is used to abbreviate the Lambda Expression expression. How is it in details?
Suppose you are working with a Lambda Expression like this:
1 |
(args) -> new ClassName(args) |
In this expression Lambda Expression, the body part we have only a code for initializing a new object with the constructor having or not having argument parameters.
To be concise, we can use the constructor reference as follows:
1 |
ClassName::new |
For the example of this constructor reference, I will use some of the interfaces in the java.util.function package.
With the constructor without parameters, we will use the Supplier interface with the Lambda Expression expression as follows:
1 |
Supplier<List<String>> s = () -> new ArrayList<>(); |
Rewrite with the constructor reference:
1 |
Supplier<List<String>> s = ArrayList::new; |
Given a constructor with a parameter, we will use the Function interface with the Lambda Expression expression as follows:
1 |
Function<String, Integer> f = s -> new Integer(s); |
Rewrite with the constructor reference:
1 |
Function<String, Integer> f = Integer::new; |