【问题标题】:java Convert lambda expression predicate to method reference?. Predicate<String> endsWith= str-> str.endsWith("a"); [duplicate]java 将 lambda 表达式谓词转换为方法引用?谓词<String> endsWith= str-> str.endsWith("a"); [复制]
【发布时间】:2019-02-15 06:46:02
【问题描述】:

请告诉我。我正在阅读方法参考,其中提到了 lambda 表达式的另一种方法并展示了一些示例,但是当我尝试将自己的谓词转换为方法参考时,我无法做到。

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

返回值。

如何与方法引用相同的转换??

提前致谢

【问题讨论】:

    标签: java java-8


    【解决方案1】:

    您只能在以下情况下使用方法引用:

    • 方法只有一个参数

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

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

    • 方法没有参数

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

    【讨论】:

    • @BoristheSpider 你是对的。会解决的。
    • 您的回答非常具体到问题的Predicate 用例。方法引用可以有任意数量的参数,只要它与目标接口确定的函数签名相匹配。或者少一个,对于非static 方法,当接收者成为隐式参数时。
    猜你喜欢
    • 2021-10-21
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多