Search code examples
javaloopsselenium-webdriverpattern-matchingvavr

How to find WebElement in a List<WebElement> by text?


I want to find WebElement in a List<WebElements> by text. My method has such arguments: List<WebElement> webElements, String text. For matching text I prefer to use javaslang library. So, what we have:

protected WebElement findElementByText(List<WebElement> webelements, String text) {

}

Using javaslang I wrote such simple matching:

Match(webElement.getText()).of(
     Case(text, webElement),
          Case($(), () -> {
               throw nw IllegalArgumentException(webElement.getText() + " does not match " + text);
          })
);

I do not understand how in good way to write a loop for finding WebElement in a List<WebElemnt> by text. Thank you guys for help.


Solution

  • I suggest to do it like this:

    // using javaslang.collection.List
    protected WebElement findElementByText(List<WebElement> webElements, String text) {
        return webElements
                .find(webElement -> Objects.equals(webElement.getText(), text))
                .getOrElseThrow(() -> new NoSuchElementException("No WebElement found containing " + text));
    }
    
    // using java.util.List
    protected WebElement findElementByText(java.util.List<WebElement> webElements, String text) {
        return webElements
                .stream()
                .filter(webElement -> Objects.equals(webElement.getText(), text))
                .findFirst()
                .orElseThrow(() -> new NoSuchElementException("No WebElement found containing " + text));
    }
    

    Disclaimer: I'm the creator of Javaslang