I have a sample code like below, I can write it and know what will it work like. But I still have some difficult on understand what java did that convert something using :: to a typical method.
.collect(ConcurrentHashMap::newKeySet,Set::add,Set::addAll)
The first parameter is Supplier<R> supplier
, I can understand this like there is a Supplier instance which get()
method has same implementation with ConcurrentHashMap::newKeySet
.
The second and third parameter are 'BiConsumer', if I use lambda expression, I will write something like (a,b)->a.add(b)
. when I wrote Set::add
, how they know convert first parameter a to Set and then invoke add()
method on it.
Definition of BiConsumer is a simple method with two parameter.
If there is some like, I won't feel hard to understand:
Set<String> set = new HashSet<>();
Consumer<String> consumer = set::add;
I just cannot understand how they know to invoke the add method on first parameter.