Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - how to use predicate with operators?

Suppose I have the following code:

public int getNumOfPostInstancesByTitle(String postMainTitle) {
    int numOfIns = 0;
    List<WebElement> blogTitlesList = driver.findElements(blogTitleLocator);

    for (WebElement thisBlogTitle : blogTitlesList) {
        String currentTitle = thisBlogTitle.getText();
        if (currentTitle.equalsIgnoreCase(postMainTitle)) {
            numOfIns++;
        }
    }
    return numOfIns;
}

what is the proper way converting it with predicate lambda?

like image 500
Nimrod Avatar asked Aug 05 '26 11:08

Nimrod


1 Answers

You can calculate your numOfInts with a simple combination of map, filter and count :

return driver.findElements(blogTitleLocator)
             .stream()
             .map(WebElement::getText) // convert to a Stream of String
             .filter(s -> s.equalsIgnoreCase(postMainTitle)) // accept only Strings
                                                             //equal to postMainTitle
             .count(); // count the elements of the Stream that passed the filter
like image 192
Eran Avatar answered Aug 07 '26 01:08

Eran