【发布时间】:2021-02-05 14:12:54
【问题描述】:
我正在研究这个函数式接口主题,我研究如何使用预定义的函数式接口:谓词和函数。
所以我创建了几个实现:
public static Predicate<String> isStringEmpty = String::isEmpty;
public static Predicate<String> isStringNotEmpty = isStringEmpty.negate();
public static Predicate<ArrayList> arrayListIsEmpty = ArrayList::isEmpty;
public static Predicate<ArrayList> arrayListIsNotEmpty = arrayListIsEmpty.negate();
public static Predicate<String> stringStartsWithA = s -> s.startsWith("A");
public static Predicate<Integer> largerThanNine = n -> n > 9;
public static Function<WebElement, String> getWebElementText = WebElement::getText;
//etc.
然后我继续在我的代码中使用它们。 例如:
isStringEmpty.negate().test("asd");
isStringNotEmpty.test("asd");
stringStartsWithA.negate().test("asd");
isStringNotEmpty.and(isStringEmpty).negate().test("aaa");
csvLine = getWebElementText.apply(leaugeRowElement);
我不明白使用这种形式的测试条件或调用函数有什么好处? (我确定有这样的!)
这与简单地调用常规函数来完成这些任务有何不同?
是否允许 lambdas 使用它们?是否允许将它们作为方法参数传递?
我很明显地错过了这种技术的真正原因。
你能解释一下吗?
谢谢!
【问题讨论】:
-
"例如:" 与其他事物相比,您只能真正声称某事物的优势。对于这些,您有什么替代方案?
-
这与简单地调用常规函数来执行这些任务有什么不同?如果您想将方法传递给另一个方法并让该方法调用它怎么办?跨度>
-
又一个教科书没有从正确的角度解释函数式接口和lambdas的案例。
标签: java java-8 functional-programming functional-interface