Java Collection Framework in Selenium
In Selenium WebDriver, Java collections play a crucial role in managing and manipulating data such as lists of web elements, handling dynamic content, or storing test results. Some of the important Java Collections Frameworks commonly used in Selenium are-
List
The List interface is one of the most used collections in Selenium. It allows you to store elements in a specific order, and the elements can be accessed by their index. This is especially useful when handling dynamic elements on a webpage, such as a list of checkboxes or links.
Common Use in Selenium:
Arraylist
It implements the List interface and provides a dynamic array-like structure that can grow and shrink in size. It is part of the java.util package
Key Features of ArrayList:
Constructor of ArrayList:
Basic Operations:
//Syntax for loop
for (String lang : list) {
??? System.out.println(lang);
}
//Syntax Using iterator concept
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
??? System.out.println(iterator.next());
}
A Basic Program
import java.util.ArrayList;
public class ArrayListBasicOperation {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();
// 1. Add elements
list.add("Hello World!");
list.add("This is ArrayList1");
list.add("This is ArrayList2");
list.add("This is ArrayList3");
System.out.println("Added elements to List: " + list);
// 2. Access elements
System.out.println("Element at index 1: " + list.get(1));
// 3. Update an element
list.set(2, "This is ArrayList2.1");
System.out.println("List after update: " + list);
// 4. Remove an element by index
list.remove(3); // Removes "Grapes"
System.out.println("List after removing element at index 3: " + list);
// 5. Remove an element by value
list.remove("This is ArrayList3"); // Removes "Banana"
System.out.println("List after removing 'This is ArrayList3': " + list);
// 6. Check if the list contains an element
boolean containsApple = list.contains("Hello World!");
System.out.println("List contains 'Hello': " + containsApple);
// 7. Get the size of the ArrayList
int size = list.size();
System.out.println("Size of the list: " + size);
// 8. Iterate through the ArrayList using a for-each loop
System.out.println("Iterating through the list:");
for (String fruit : list) {
System.out.println(fruit);
}
// 9. Clear all elements from the list
list.clear();
System.out.println("List after clearing all elements: " + list);
}
}
//output
Added elements to List: [Hello World!, This is ArrayList1, This is ArrayList2, This is ArrayList3]
Element at index 1: This is ArrayList1
List after update: [Hello World!, This is ArrayList1, This is ArrayList2.1, This is ArrayList3]
List after removing element at index 3: [Hello World!, This is ArrayList1, This is ArrayList2.1]
List after removing 'This is ArrayList3': [Hello World!, This is ArrayList1, This is ArrayList2.1]
List contains 'Hello': true
Size of the list: 3
Iterating through the list:
Hello World!
This is ArrayList1
This is ArrayList2.1
List after clearing all elements: []
Array list in Selenium
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSearch {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
driver = new EdgeDriver();
// Create an ArrayList to store search queries
ArrayList<String> searchQueries = new ArrayList<>();
searchQueries.add("Prime Misnister Of Inida");
searchQueries.add("Java Programming");
searchQueries.add("ArrayList in Java");
for (String MyQuery : searchQueries) {
// Navigate to Google
driver.get("https://www.google.com");
driver.manage().window().maximize();
// Find the search box and input the search query
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.clear(); // Clear any previous search input
searchBox.sendKeys(MyQuery); // Enter the search query
// Submit the search (press Enter)
searchBox.submit();
Thread.sleep(2000);
// Get the search results and store them in a list (ArrayList)
List<WebElement> results = driver.findElements(By.cssSelector("h3"));
System.out.println("Search results for: " + MyQuery);
for (WebElement result : results) {
Thread.sleep(2000);
System.out.println(result.getText()); // Print each result title
}
System.out.println("______________________________________");
}
driver.quit();
}
}
//please note-while executing this script , you will get captcha , you need to handle captcha !
?Set
A Set is a collection that does not allow duplicate elements. In Selenium, HashSet and LinkedHashSet are often used when the order of elements doesn't matter but uniqueness is important.
Common Use in Selenium:
Example:
// Storing unique links' texts in a Set to avoid duplicates
Set<String> uniqueLinksText = new HashSet<>();
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
??? uniqueLinksText.add(link.getText());
}
System.out.println("Unique Link Texts: " + uniqueLinksText);
Map
The Map interface stores key-value pairs. In Selenium, you might use a HashMap or LinkedHashMap to store data related to web elements, such as mapping element locators to their respective actions or storing configuration data like test case IDs and their corresponding results.
Common Use in Selenium:
Example:
// Mapping actions to web elements
Map<String, WebElement> elementActions = new HashMap<>();
elementActions.put("SubmitButton", driver.findElement(By.id("submitBtn")));
elementActions.put("SearchBox", driver.findElement(By.id("searchBox")));
?
// Performing actions based on the map
elementActions.get("SubmitButton").click();
领英推荐
elementActions.get("SearchBox").sendKeys("Selenium WebDriver");
Queue
A Queue is typically used for holding elements in a specific order for processing. In Selenium, Queue is rarely used directly for web element operations, but it may be helpful for scheduling tasks or managing test execution in certain frameworks.
Common Use in Selenium:
Example:
// Using LinkedList as Queue to store actions for sequential processing
Queue<String> actionsQueue = new LinkedList<>();
actionsQueue.add("openURL");
actionsQueue.add("login");
actionsQueue.add("search");
?
while (!actionsQueue.isEmpty()) {
??? String action = actionsQueue.poll();
??? // Perform actions based on the action in the queue
}
?Iterable
The Iterable interface is the root of the collection hierarchy and is implemented by most collection classes. In Selenium, this interface is frequently used with the for-each loop (enhanced loop) for iterating through collections such as lists or sets.
Common Use in Selenium:
Example:
// Iterating over list of WebElements using Iterable
List<WebElement> checkboxes = driver.findElements(By.xpath("https://input[@type='checkbox']"));
for (WebElement checkbox : checkboxes) {
??? if (!checkbox.isSelected()) {
??????? checkbox.click();
??? }
}
Concurrent Collections
For multithreaded testing in Selenium (such as when performing parallel test execution using frameworks like TestNG or JUnit), concurrent collections like ConcurrentHashMap and CopyOnWriteArrayList are useful for managing data in a thread-safe way.
Common Use in Selenium:
Example:
// Using ConcurrentHashMap for thread-safe data access
ConcurrentHashMap<String, String> resultsMap = new ConcurrentHashMap<>();
resultsMap.put("Test1", "Pass");
resultsMap.put("Test2", "Fail");
System.out.println(resultsMap);
Summary of Key Java Collections in Selenium-
List -Handling lists of web elements (e.g., links, checkboxes)
Set -Storing unique web elements or data (e.g., unique texts)
Map -Storing element locators with actions, mapping data
Queue -Managing actions or tasks in order, handling windows/tabs
Iterable -Iterating over collections of elements or test data
Concurrent Collections -Managing data in multithreaded or parallel testing
Collections Class -Sorting, shuffling, and reversing collections
These collections are essential for effectively handling data and operations within Selenium WebDriver tests, especially when dealing with large sets of web elements or when working in parallel test environments.