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

Nim*_*rod 10 java lambda predicate java-8 java-stream

我有以下代码:

public boolean isImageSrcExists(String imageSrc) {
    int resultsNum = 0;
    List<WebElement> blogImagesList = driver.findElements(blogImageLocator);

    for (WebElement thisImage : blogImagesList) {
        if (thisImage.getAttribute("style").contains(imageSrc)) {
            resultsNum++;
        }
    }

    if (resultsNum == 2) {
        return true;
    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Bor*_*der 12

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

但你可以......

...创建一个方法,返回一个布尔值,并将调用编码为getAttribute("style"):

public boolean getAttribute(final T t) {
    return t.getAttribute("style");
}
Run Code Online (Sandbox Code Playgroud)

这将允许您使用方法ref:

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

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

final Function<T, R> mapper = t -> t.getAttribute("style");
Run Code Online (Sandbox Code Playgroud)

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

int a = (int) blogImagesList.stream()
              .map(mapper)
              .filter(s -> s.contains(imageSrc))
              .count();
Run Code Online (Sandbox Code Playgroud)

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

public Function<T,R> toAttributeExtractor(String attrName) {
    return t -> t.getAttribute(attrName);
}
Run Code Online (Sandbox Code Playgroud)

然后你需要打电话toAttributeExtractor来获得一个Function并将其传递到map:

final Function<T, R> mapper = toAttributeExtractor("style");
int a = (int) blogImagesList.stream()
              .map(mapper)
              .filter(s -> s.contains(imageSrc))
              .count();
Run Code Online (Sandbox Code Playgroud)

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

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


Era*_*ran 7

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

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

  • 我冒昧地格式化代码,因此您可以在不滚动的情况下阅读它. (3认同)