问题描述
我正在研究这个函数式接口主题,并且我正在研究如何使用预定义的函数式接口:谓词和函数。
所以我创建了几个实现:
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);
我无法理解使用这种测试条件或调用函数的形式有什么好处? (我肯定有这样的!)
是否允许 lambda 使用它们?是否允许将它们作为方法参数传递?
我很想念这种技术的真正原因。
你能解释一下吗?
谢谢!
解决方法
如果您阅读有关函数式接口和 lambda 的手册,您的问题可能会得到解答。 看看 lambda 表达式和通常的匿名类创建之间的区别。两个变量的使用方式相同。
//using anonymous class
Predicate<String> isStringEmptyObj = new Predicate<String>() {
@Override
public boolean test(String o) {
return o.isEmpty();
}
};
System.out.println(isStringEmptyObj.negate().test("asd"));
//using lambda with reference to existing String object method
Predicate<String> isStringEmpty = String::isEmpty;
System.out.println(isStringEmpty.negate().test("asd"));