我希望使用和了解Predicate和Lambda表达式。特别是与硒一起使用。
想象一下,您有一个WebElements的大量选择(List),并且您希望对其应用谓词过滤器,以便列表更小。
我是否在正确的轨道上1,2,3以下我会做出哪些改变?
List<WebElement> webElements = driver.findElements(By.cssSelector(".someClassName")); // returns large list
// then try and filter down the list
Predicate<WebElement> hasRedClass -> Predicate.getAttribute("class").contains("red-background");
Predicate<WebElement> hasDataToggleAttr -> Predicate.getAttribute("data-toggle").size() > 0;
// without predicate probably looks like this
//driver.findElements(By.cssSelector(".someClassName .red-background"));
// 1. this is what I think it should look like???
List<WebElement> webElementsWithClass = webElements.filter(hasRedClass);
// 2. with hasDataToggleAttr
List<WebElement> webElementsWithDataToggleAttr = webElements.filter(hasDataToggleAttr);
// 3. with both of them together...
List<WebElement> webElementsWithBothPredicates = webElements.filter(hasRedClass, hasDataToggleAttr);
答案 0 :(得分:2)
我希望这就是你要找的东西:
List<WebElement> webElements = driver.findElements(By.cssSelector(".someClassName")); // returns large list
// then try and filter down the list
Predicate<WebElement> hasRedClass = we -> we.getAttribute("class").contains("red-background");
Predicate<WebElement> hasDataToggleAttr = we -> we.getAttribute("data-toggle").length() > 0;
// without predicate probably looks like this
//driver.findElements(By.cssSelector(".someClassName .red-background"));
// 1. this is what I think it should look like???
List<WebElement> webElementsWithClass = webElements.stream()
.filter(hasRedClass).collect(Collectors.toList());
// 2. with hasDataToggleAttr
List<WebElement> webElementsWithDataToggleAttr = webElements.stream()
.filter(hasDataToggleAttr).collect(Collectors.toList());
// 3. with both of them together...
List<WebElement> webElementsWithBothPredicates = webElements.stream()
.filter(hasDataToggleAttr.and(hasRedClass)).collect(Collectors.toList());