Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameters in method reference [duplicate]

Is possible to pass parametres using method reference? For example, I have to create a TreeMap but using reverseOrder(). Does something like TreeMap::new(reverseOrder()) exist?

like image 965
Vincenzo Cosi Avatar asked Jul 02 '17 10:07

Vincenzo Cosi


People also ask

Can we pass parameter in method reference?

Static method reference operator, we use the :: operator, and that we don't pass arguments to the method reference. In general, we don't have to pass arguments to method references.

Can a method have two parameters?

Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

How do you reference a parameter from a method in Java?

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

What is the difference between a method reference and a lambda expression?

Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it.


2 Answers

No, you can't do it with a method reference.

You can use lambda expressions instead:

() -> new TreeMap<TheRelevantType>(reverseOrder())

or

() -> new TreeMap<>(reverseOrder())

if you are using this expression in a context where the compiler can infer the element type of the TreeMap.

like image 106
Eran Avatar answered Sep 22 '22 17:09

Eran


You need a lambda expression for that... you are probably thinking about a Supplier:

() -> new TreeMap<>(Comparator.reverseOrder())
like image 21
Eugene Avatar answered Sep 24 '22 17:09

Eugene