[英]Java 8 - How to use predicate that has a function with parameter?
我有以下代碼:
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();
您無法完全按照自己的意願執行操作 - 方法引用中不允許使用顯式參數。
但你可以......
...創建一個返回布爾值的方法,並對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();
...或者你可以把上面兩種方法結合起來(這肯定是可怕的過度殺傷力)
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();
您不能將參數傳遞給方法引用。 您可以使用lambda表達式:
int a = (int) blogImagesList.stream()
.map(w -> w.getAttribute("style"))
.filter(s -> s.contains(imageSrc))
.count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.