Working with Collections in Java for Selenium Testing
In Selenium automation, collections help you store, organize, and manipulate groups of WebElements or data extracted from a webpage. Java Collections such as List, Set, and Map are frequently used to manage this data efficiently.
1. Why Collections Are Important in Selenium
You often need collections to:
Store multiple WebElements returned by findElements()
Loop through list items, table rows, or dropdown options
Remove duplicates
Sort extracted texts
Map key-value pairs (e.g., columnName → value)
Validate expected vs. actual UI values
2. Using List<WebElement> in Selenium
Example: Getting all links on a page
List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement link : links) {
System.out.println(link.getText());
}
Convert WebElements to List<String>
List<String> linkTexts = new ArrayList<>();
for (WebElement link : links) {
linkTexts.add(link.getText());
}
Using Streams (Java 8+)
List<String> linkTexts = links.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
3. Using Set to Remove Duplicate Values
Example: Get unique dropdown options
Select select = new Select(driver.findElement(By.id("country")));
List<WebElement> options = select.getOptions();
Set<String> uniqueCountries = new HashSet<>();
for (WebElement option : options) {
uniqueCountries.add(option.getText());
}
System.out.println("Unique countries: " + uniqueCountries);
4. Using Map for Key-Value Storage
Maps are useful when you need to associate values—such as field names and their extracted values.
Example: Mapping table headers to row data
List<WebElement> headers = driver.findElements(By.xpath("//table/thead/tr/th"));
List<WebElement> row = driver.findElements(By.xpath("//table/tbody/tr[1]/td"));
Map<String, String> rowData = new HashMap<>();
for (int i = 0; i < headers.size(); i++) {
rowData.put(headers.get(i).getText(), row.get(i).getText());
}
System.out.println(rowData);
5. Sorting Collections
Example: Sort extracted texts
List<WebElement> items = driver.findElements(By.className("product-name"));
List<String> productNames = items.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
Collections.sort(productNames); // ascending
Descending Sort
Collections.sort(productNames, Collections.reverseOrder());
6. Filtering Elements with Streams
Example: Get visible elements only
List<WebElement> visibleItems = items.stream()
.filter(WebElement::isDisplayed)
.collect(Collectors.toList());
7. Extracting Only Specific Elements
Example: Get all prices (filter by pattern)
List<WebElement> prices = driver.findElements(By.className("price"));
List<Double> numericPrices = prices.stream()
.map(e -> Double.parseDouble(e.getText().replace("$","")))
.collect(Collectors.toList());
8. Using Collections for Assertions
Example: Validate expected vs. actual list
List<String> expected = Arrays.asList("Home", "About", "Contact");
List<String> actual = driver.findElements(By.cssSelector(".menu li"))
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
Assert.assertEquals(actual, expected);
9. Removing Empty or Null Values
List<String> cleaned = actual.stream()
.filter(s -> s != null && !s.trim().isEmpty())
.collect(Collectors.toList());
10. Practical Use Cases in Selenium
Use Case Collection Used Purpose
List of WebElements List Iterate, extract, validate
Removing duplicates Set Unique values
Mapping table data Map Key-value storage
Sorting dropdown options List + sort UI validation
Extracting attributes (like href) List Data extraction
Filtering elements Stream More readable logic
Summary
Java Collections are extremely useful in Selenium testing because they allow you to:
Handle multiple web elements efficiently
Clean, transform, and compare data
Validate UI values easily
Apply sorting, filtering, and grouping operations
Mastering Collections + Selenium strengthens both your coding ability and automation testing skills.
Learn Selenium with JAVA Training in Hyderabad
Read More
Handling Exceptions in Selenium Test Scripts
Using Loops and Conditions to Control Test Flow
Java Basics for Selenium Testers
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments