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?
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.
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.
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.
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.
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
.
You need a lambda expression for that... you are probably thinking about a Supplier
:
() -> new TreeMap<>(Comparator.reverseOrder())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With