Java 8 - 如何使用带参数函数的谓词? [英] Java 8 - How to use predicate that has a function with parameter?

查看:121
本文介绍了Java 8 - 如何使用带参数函数的谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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;
    }
}

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

What is the proper way of converting it to use Java 8 Streams?

当我尝试使用 map(),我收到错误,因为 getAttribute 不是函数

When I'm trying to use map(), I get an error since getAttribute isn't a Function.

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


推荐答案

你无法做到你想要的 - 显式参数是方法引用中不允许。

You cannot do exactly what you want - explicit parameters are not allowed in method references.

但是你可以......

But you could...

...创建一个返回的方法布尔和编码调用 getAttribute(style)

...create a method that returns a boolean and harcoded the call to getAttribute("style"):

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

这将允许您使用方法ref:

This would allow you to use the method ref:

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

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

...or you could define a variable to hold the function:

final Function<T, R> mapper = t -> t.getAttribute("style");

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

This would allow you to simply pass the variable

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

...或者你可以讨论并结合上述两种方法(这肯定是可怕的过度杀伤)

...or you could curry and combine the above two approaches (this is certainly horribly overkill)

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

然后你需要调用 toAttributeExtractor 获取功能并将其传递到地图

Then you would need to call toAttributeExtractor to get a Function and pass that into the map:

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

虽然实际上,简单地使用lambda会更容易(就像你在下一行一样):

Although, realistically, simply using a lambda would be easier (as you do on the next line):

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

这篇关于Java 8 - 如何使用带参数函数的谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆