我有以下代码:
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 Stream
的正确方法是什么?
当我尝试使用 map()
时,出现错误,因为 getAttribute
不是 Function
。
int a = (int) blogImagesList.stream()
.map(WebElement::getAttribute("style"))
.filter(s -> s.contains(imageSrc))
.count();
最佳答案
您不能完全按照您的意愿行事 - 方法引用中不允许显式参数。
但是你可以...
...创建一个返回 boolean 值的方法并对 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<T, R> mapper = t -> t.getAttribute("style");
这将允许您简单地传递变量
int a = (int) blogImagesList.stream()
.map(mapper)
.filter(s -> s.contains(imageSrc))
.count();
...或者您可以柯里化(Currying)并结合上述两种方法(这肯定是太过分了)
public Function<T,R> toAttributeExtractor(String attrName) {
return t -> t.getAttribute(attrName);
}
然后您需要调用 toAttributeExtractor
来获取 Function
并将其传递到 map
中:
final Function<T, R> 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();
关于Java 8 - 如何使用具有参数函数的谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332428/