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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Method references are described here: docs.oracle.com/javase/tutorial/java/javaOO/…
Thanks. I kinda guessed that. I was wondering what are the rules for using a method as a functional interface?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.