From Selenium 3.0, minimum Java version is 8. In this blog article, we would like to show you how to use Java 8 features like Lambda expression and Collections Stream to simplify Selenium WebDriver snippets.
Let’s start with Lambda expression.
Java lambda expressions are Java’s first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.
Source: Tutorials Jenkov
Let’s say you want to print all the elements from an array list without lambda expression; then you will come up with the below snippet.
List list=new ArrayList(); list.add("Selenium"); list.add("UFT"); list.add("Appium"); for(String item:list){ System.out.println(item); }
The same logic, we can implement a lot easier with lambda expression in Java 8.
list.forEach(item -> System.out.println(item));
Collections Stream
Collections Stream is a new feature in Java 8. A stream represents a sequence of elements and supports different kind of operations from a collection.
Let’s say you want to check whether an option is available or not in a drop-down list.
Select select=new Select(driver.findElement(By.id("drp1"))); //Validating drop-down option without For Loop select.getOptions().stream().anyMatch(item->item.getText().equals("Option1"))
Filtering WebElements using Regular Expression
driver.get("file:///C:/sample.html"); List<WebElement> elements=driver.findElements( By.xpath("//input[@type='checkbox']")); elements.stream() .filter(element->Pattern.compile("check_(\d+)_box").matcher(element.getAttribute("id")).matches()) .forEach(element->element.click());
Getting a visible WebElement from WebElement List
driver.findElements(By.xpath("//input")) .stream() .filter(elemnt -> elemnt.isDisplayed()) .findFirst() .get() .sendKeys("codoid-testing company");
Very Simple, isn’t it?
Comments(0)