http://www.baeldung.com/java-8-double-colon-operator
:: -> Method References
From Lambdas to Double Colon Operator
With Lambdas expressions, we’ve seen that code can become very concise.
For example, to create a comparator, the following syntax is enough:
1
| Comparator c = (Computer c1, Computer c2) -> c1.getAge().compareTo(c2.getAge()); |
Then, with type inference:
1
| Comparator c = (c1, c2) -> c1.getAge().compareTo(c2.getAge()); |
But can we make the code above even more expressive and readable? Let’s have a look:
1
| Comparator c = Comparator.comparing(Computer::getAge); |
We’ve used the :: operator as shorthand for lambdas calling a specific method – by name. And the end, result is of course even more readable syntax.
List inventory = Arrays.asList(
new
Computer(
2015
,
"white"
,
35
),
new
Computer(
2009
,
"black"
,
65
));
inventory.forEach(ComputerUtils::repair);
Computer c1 =
new
Computer(
2015
,
"white"
);
Computer c2 =
new
Computer(
2009
,
"black"
);
Computer c3 =
new
Computer(
2014
,
"black"
);
Arrays.asList(c1, c2, c3).forEach(System.out::print);
public
Double calculateValue(Double initialValue) {
return
initialValue/
1.50
;
}
@Override
public
Double calculateValue(Double initialValue){
Function<Double, Double> function =
super
::calculateValue;
Double pcValue = function.apply(initialValue);
return
pcValue + (initialValue/
10
) ;
}
@FunctionalInterface
public
interface
InterfaceComputer {
Computer create();
}
InterfaceComputer c = Computer::
new
;
Computer computer = c.create();
BiFunction<Integer, String, Computer> c4Function = Computer::
new
;
Computer c4 = c4Function.apply(
2013
,
"white"
);
If parameters are three or more you have to define a new Functional interface:
1
2
3
4
5
6
7
8
@FunctionalInterface
interface
TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
default
<V> TriFunction<A, B, C, V> andThen( Function<?
super
R, ?
extends
V> after) {
Objects.requireNonNull(after);
return
(A a, B b, C c) -> after.apply(apply(a, b, c));
}
}
Then, initialize your object:
1
2
TriFunction <Integer, String, Integer, Computer> c6Function = Computer::
new
;
Computer c3 = c6Function.apply(
2008
,
"black"
,
90
);
Create an array
Function <Integer, Computer[]> computerCreator = Computer[]::
new
;
Computer[] computerArray = computerCreator.apply(
5
);
The double colon operator – introduced in Java 8 – will be very useful in some scenarios, and especially in conjunction with Streams.
It’s also quite important to have a look at functional interfaces for a better understanding of what happens behind the scenes.
No comments:
Post a Comment