This question already has an answer here:
- :: (double colon) operator in Java 8 17 answers
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 theconcat()
method of the String class.A
BiFunction
is a functional interface with a single methodapply
that accepts two parameters (the first of typeT
and the second of typeU
), and returns a result of typeR
(in other words, the interfaceBiFunction<T,U,R>
has a methodR apply(T t, U u)
).map.merge
expects aBiFunction<? super V,? super V,? extends V>
as the third parameter, whereV
is the value of theMap
. If you have aMap
with aString
value, you can use any method that accepts twoString
parameters and returns aString
.String::concat
satisfies these requirements, and that's why it can be used inmap.merge
.The reason it satisfies these requirements requires an explanation :
The signature of
String::concat
ispublic 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 thestr
parameter) and a result of type String.