7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
yesennes
  • 1,147
  • 1
  • 10
  • 19

1 Answers1

5

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    Method references are described here: http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html – clstrfsck Jul 18 '14 at 01:58
  • Thanks. I kinda guessed that. I was wondering what are the rules for using a method as a functional interface? – yesennes Jul 18 '14 at 02:00