Answer the question
In order to leave comments, you need to log in
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));
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());
Answer the question
In order to leave comments, you need to log in
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.someField
Similarly, 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 println
returned 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 .
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.
:: 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 questionAsk a Question
731 491 924 answers to any question