I was looking at some of the changes made to the Java SE API with 1.8, and I when looking at the new method Map.merge it shows an example of how to use it with the line
map.merge(key, msg, String::concat)
I understand how to use a lambda expressions to create anonymous functional interfaces, but this seems to use a method as a BiFunction. I like to understand and use obscure java syntaxes, but I can't find any mention of this one anywhere.
String::concat
is a reference to the concat()
method of the String class.
A BiFunction
is a functional interface with a single method apply
that accepts two parameters (the first of type T
and the second of type U
), and returns a result of type R
(in other words, the interface BiFunction<T,U,R>
has a method R apply(T t, U u)
).
map.merge
expects a BiFunction<? super V,? super V,? extends V>
as the third parameter, where V
is the value of the Map
. If you have a Map
with a String
value, you can use any method that accepts two String
parameters and returns a String
.
String::concat
satisfies these requirements, and that's why it can be used in map.merge
.
The reason it satisfies these requirements requires an explanation :
The signature of String::concat
is public String concat(String str)
.
This can be seen as a function with two parameters of type String (this
, the instance for which this method is called, and the str
parameter) and a result of type String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With