2

I am looking to use and learn about the Predicate and Lambda expression. In particular using it with selenium.

Imagine you have a large selection(List) of WebElements and you want to apply a predicate filter to it so that the list is smaller .

Am I on the right track for 1,2,3 below what changes would I meed to make?

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);
Robbo_UK
  • 11,351
  • 25
  • 81
  • 117
  • 4
    Maybe you should study [the tutorials](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) and get a basic idea of the syntax first. – Holger May 11 '15 at 18:33
  • 2
    And please clarify what exactly you are asking. As your question stands now you are asking a yes/no question. – K Erlandsson May 11 '15 at 18:43
  • I have read a couple of tutorials and now im trying to piece it together. @kristoffer I have updated the question. I am basically looking to correct my attempts labelled 1,2,3 – Robbo_UK May 11 '15 at 18:50

1 Answers1

3

I hope here is what you are looking for:

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());
ytterrr
  • 3,036
  • 6
  • 23
  • 32