Java 8 - 如何将谓词与运算符一起使用?

Java 8 - how to use predicate with operators?

假设我有以下代码:

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 转换它的正确方法是什么?

您可以使用 mapfiltercount 的简单组合来计算您的 numOfInts :

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