Java 8 – 如何使用带参数函数的谓词?

我有以下代码:

public boolean isImageSrcExists(String imageSrc) { int resultsNum = 0; List blogImagesList = driver.findElements(blogImageLocator); for (WebElement thisImage : blogImagesList) { if (thisImage.getAttribute("style").contains(imageSrc)) { resultsNum++; } } if (resultsNum == 2) { return true; } else { return false; } } 

将其转换为使用Java 8 Stream的正确方法是什么?

当我尝试使用map() ,我得到一个错误,因为getAttribute不是一个Function

 int a = (int) blogImagesList.stream() .map(WebElement::getAttribute("style")) .filter(s -> s.contains(imageSrc)) .count(); 

您无法完全按照自己的意愿执行操作 – 方法引用中不允许使用显式参数。

但你可以……

…创建一个返回布尔值的方法,并对getAttribute("style")的调用进行编码:

 public boolean getAttribute(final T t) { return t.getAttribute("style"); } 

这将允许您使用方法ref:

 int a = (int) blogImagesList.stream() .map(this::getAttribute) .filter(s -> s.contains(imageSrc)) .count(); 

…或者你可以定义一个变量来保存函数:

 final Function mapper = t -> t.getAttribute("style"); 

这将允许您简单地传递变量

 int a = (int) blogImagesList.stream() .map(mapper) .filter(s -> s.contains(imageSrc)) .count(); 

…或者你可以把上面两种方法结合起来(这肯定是可怕的过度杀伤力)

 public Function toAttributeExtractor(String attrName) { return t -> t.getAttribute(attrName); } 

然后你需要调用toAttributeExtractor来获取一个Function并将其传递给map

 final Function mapper = toAttributeExtractor("style"); int a = (int) blogImagesList.stream() .map(mapper) .filter(s -> s.contains(imageSrc)) .count(); 

虽然,实际上,简单地使用lambda会更容易(正如你在下一行中所做的那样):

 int a = (int) blogImagesList.stream() .map(t -> t.getAttribute("style")) .filter(s -> s.contains(imageSrc)) .count(); 

您不能将参数传递给方法引用。 您可以使用lambda表达式:

 int a = (int) blogImagesList.stream() .map(w -> w.getAttribute("style")) .filter(s -> s.contains(imageSrc)) .count();