F
F
fh2018-11-09 22:16:21
Java
fh, 2018-11-09 22:16:21

Colon operator (::) java, what is the working principle?

The usual lambda function a -> foo(a)works clearly and logically, unlike the colon operator. Here are two examples:
1st example:

// с использованием ::
list.forEach(System.out::println); 
// то же самое, но обычной лямбдой
list.forEach(n -> System.out.println(n));

Based on this example, we can say that (::) takes only one argument and automatically substitutes it in the println function of the System.out class.
And now 2 examples:
map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey);
// Исходя из логики первого примера, эквивалентно, используя лямбду, можно было бы заменить так:
map.entrySet().stream().collect(Collectors.toMap(a -> Map.Entry.getKey(a)); // однако очевидно, что это неправильно, и правильно будет так:
map.entrySet().stream().collect(Collectors.toMap(a -> a.getKey());

Hence the questions:
how does :: determine exactly how a method should be called (System.out.println(n) or n.getKey() )?
how can :: work with multiple arguments?
what is his principle of operation?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2018-11-10
@ramazan793

First of all, quadratic is an operator, not a function. Therefore, it does not accept any arguments. It has a left part of an expression and a right part of an expression, like the dot operator, for example. The dot operator allows you to get the value of the field specified on the right side of the expression, the class specified on the left - SomeClass.someFieldSimilarly, the square dot allows you to get a link to the method specified on the right side of the class specified on the left.
The compiler infers the type of the reference from the context and casts it to the appropriate functional interface . In particular, the forEach method accepts a Consumer<? super T> , to it will be given a reference to the method printlnreturned by the expressionSystem.out::println
At the VM level, both method references and lambdas are runtime-created proxy classes. You can see an example of their generation and composition here .

M
Maxim Moseychuk, 2018-11-09
@fshp

This is a link to a method. You can get a reference to a method with any number of parameters.
But you can substitute it only where it fits the type.

D
Daniel Demidko, 2018-11-10
@DanielDemidko

:: Nothing substitutes anywhere. This means that you take and send the println method CAM instead of a lambda

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question