[英]Java | Selenium | Using Stream to return single Webelement from a list of weblements
I'm trying to filter a list of webelements down to a single webelement by the elements's innerText. 我正在尝试通过元素的innerText将一个webelements列表过滤到单个webelement。 In c#, I would use a linq where clause.
在C#中,我将使用linq where子句。 In Java, I'm trying to use stream but I can't figure out why I'm getting the incompatible type error (required: org.openQA.selenium.Webelement. Found: java.util.optional)
在Java中,我尝试使用流,但无法弄清楚为什么出现不兼容的类型错误(必需:org.openQA.selenium.Webelement。找到:java.util.optional)
public List <WebElement> emp = driver.findElements(By.className("employee"));
public String correctName = driver.findElement(By.id("name")).getText();
public WebElement getName(){
WebElement correct = emp.stream().filter((element) -> element.getText().contains(correctName)).findFirst();
return correct;
}
The error is fair. 该错误是公平的。
findFirst
returns an Optional
. findFirst
返回Optional
。 You have to get the object explicitly like so. 您必须像这样显式地获取对象。
WebElement correct = emp.stream().filter((element) -> element.getText().contains(correctName)).findFirst().orElse(null);
So if the Optional
is not empty, it will return the value, otherwise it will return null
. 因此,如果
Optional
不为空,它将返回该值,否则将返回null
。 Note get
on an Optional
is not recommended to use and it'll be deprecated in future. 请注意,不建议您在
Optional
上使用get
,它会在以后被弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.