Selenium WebDriver With Java 8 – Lambda Expressions and Collections Stream

From Selenium 3.0, minimum Java version is 8. In this article, we illustrate how to use Java 8 features like Lambda expression and Collections Stream to simplify Selenium WebDriver code.

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.

Let’s say you have an ArrayList and you want to print all its elements. Without lambda expressions, you would use:

List<String> list=new ArrayList();
for(String item:list){

Using Lambda expression in Java 8, we can rewrite the same loop using forEach

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.

So, 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("selectId")));

//Validating drop-down option without For Loop

Filtering WebElements Using Regular Expression

List<WebElement> elements=driver.findElements( By.xpath("//input[@type='checkbox']"));

Leave a Reply