How to Use Java Streams in Selenium Automation
Java Streams, introduced in Java 8, provide a functional programming approach to process collections of data efficiently. In Selenium automation, Streams can simplify working with lists of web elements, filtering, mapping, and performing actions in a concise and readable way.
1. Why Use Java Streams in Selenium
Traditionally, handling multiple web elements requires loops like for or for-each. Java Streams allow:
Cleaner code with less boilerplate
Parallel execution for performance
Functional operations: filter, map, forEach, collect
Easier debugging and chaining operations
2. Common Selenium Use Cases for Streams
Filtering elements based on text or attributes
Collecting text from multiple elements
Clicking on specific elements from a list
Validating web tables or dropdown options
Performing bulk operations on elements
3. Example 1: Collect Text from Multiple Elements
Suppose you have a list of product names on a web page:
List<WebElement> products = driver.findElements(By.cssSelector(".product-name"));
// Using traditional loop
List<String> productNames = new ArrayList<>();
for (WebElement product : products) {
productNames.add(product.getText());
}
// Using Java Streams
List<String> productNamesStream = products.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
System.out.println(productNamesStream);
Explanation:
stream() converts the list into a Stream
map() transforms each WebElement into text
collect(Collectors.toList()) gathers results back into a list
4. Example 2: Filter Elements Based on Text
Filter only products containing “Laptop”:
List<WebElement> laptopProducts = products.stream()
.filter(e -> e.getText().contains("Laptop"))
.collect(Collectors.toList());
laptopProducts.forEach(e -> System.out.println(e.getText()));
Explanation:
filter() applies a condition
Only elements matching the condition are processed
5. Example 3: Click on a Specific Element
Click on a button with exact text “Buy Now”:
driver.findElements(By.tagName("button")).stream()
.filter(e -> e.getText().equals("Buy Now"))
.findFirst()
.ifPresent(WebElement::click);
Explanation:
findFirst() returns the first element matching the filter
ifPresent() safely performs an action if the element exists
6. Example 4: Working with Web Tables
Suppose you want all rows where the status column contains “Active”:
List<WebElement> rows = driver.findElements(By.cssSelector("table#users tbody tr"));
List<String> activeUsers = rows.stream()
.filter(row -> row.findElement(By.cssSelector("td.status")).getText().equals("Active"))
.map(row -> row.findElement(By.cssSelector("td.name")).getText())
.collect(Collectors.toList());
activeUsers.forEach(System.out::println);
Explanation:
Filter rows with a specific status
Map to extract the name column
Collect results into a list
7. Example 5: Parallel Streams for Faster Execution
For large lists of elements, you can use parallel streams:
List<String> allTexts = driver.findElements(By.cssSelector(".items")).parallelStream()
.map(WebElement::getText)
.collect(Collectors.toList());
Caution:
Parallel streams can improve performance
But be careful with thread safety and WebDriver commands
Avoid using them for actions like click() on the same WebDriver instance
8. Advantages of Using Streams in Selenium
Readable and concise code
Easy chaining of multiple operations (filter → map → collect)
Avoids nested loops
Functional approach reduces side effects
Supports lambda expressions for inline operations
9. Tips and Best Practices
Avoid using parallel streams for WebDriver interactions because WebDriver is not thread-safe.
Use streams for data extraction, validation, and processing.
Combine with Optional to handle elements safely.
Use method references (WebElement::getText) for cleaner code.
Keep locators efficient (use By.cssSelector or By.xpath) for faster performance.
10. Summary
Java Streams in Selenium:
Provide a functional programming approach for handling collections of elements
Make Selenium code cleaner, shorter, and more maintainable
Are excellent for filtering, mapping, and extracting data from web pages
Must be used carefully with WebDriver for actions like clicks
Using Streams allows modern Selenium automation scripts to be more readable and efficient, especially for data-heavy web pages or repetitive tasks.
Learn Selenium with JAVA Training in Hyderabad
Read More
Reading Data from Properties Files in Java
Creating Utility Classes for Common Selenium Functions
Java OOP Concepts for Selenium Testers
Working with Collections in Java for Selenium Testing
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments