假设我有以下代码:

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;
}

用谓词lambda转换的正确方法是什么?

最佳答案

您可以使用numOfIntsmapfilter的简单组合来计算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

07-27 17:02