-3

Please let me know. I was reading method reference it was mentioned that an alternative way of a lambda expression and shown some examples but when I tried to do convert my own predicate to method reference I could not able to do it.

Predicate<String> endsWith= str-> str.endsWith("a");
endsWith.test("asap"); 

returns the value.

How to convert the same as method reference ??

Thanks in advance

Naman
  • 27,789
  • 26
  • 218
  • 353

1 Answers1

0

You can only use method reference in case:

  • method have exactly one parameter

Predicate endsWith = foo::endsWith;//foo is some variable

Predicate endsWith = FooClass::endsWith;//for static methods

  • method doesn't have parameters

Predicate endsWith = FooClass::endsWith;//this method is not static

talex
  • 17,973
  • 3
  • 29
  • 66
  • 1
    @BoristheSpider You are right. Will fix it. – talex Feb 15 '19 at 06:56
  • Your answer is very specific to the question’s `Predicate` use case. A method reference can have an arbitrary number of parameters, as long as it matches the function signature determined by the target interface. Or one less, for non-`static` methods when the receiver becomes an implicit parameter. – Holger Feb 15 '19 at 09:26