Java Collection Framework in Selenium

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:

  • Handling lists of web elements (e.g., multiple links, checkboxes, buttons).
  • Iterating over lists of web elements to perform actions on each one.
  • ArrayList and LinkedList are the most used implementations of the List interface.


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:

  • Resizable Array: Unlike arrays in Java, which have a fixed size, an ArrayList can grow and shrink dynamically as elements are added or removed.
  • Ordered: The ArrayList maintains the insertion order of elements. That is, the order in which elements are inserted is the order in which they will be accessed.
  • Indexed: Elements in an ArrayList can be accessed via their index, like arrays.
  • Allows Duplicates: It allows storing duplicate values.
  • Null Elements: An ArrayList can contain null values.?

Constructor of ArrayList:

  • ArrayList(): Creates an empty ArrayList with an initial capacity of 10.
  • ArrayList(int initialCapacity): Creates an ArrayList with the specified initial capacity.
  • ArrayList(Collection<? extends E> c): Creates an ArrayList containing the elements of the specified collection.

Basic Operations:

  1. Adding Elements add(E e): Adds an element to the end of the list. add(int index, E element): Inserts an element at a specific index.
  2. Accessing Elements get(int index): Retrieves the element at the specified index. set(int index, E element): Replaces the element at the specified index.
  3. Removing Elements remove(int index): Removes the element at the specified index. remove(Object o): Removes the first occurrence of the specified element. clear(): Removes all elements from the list.
  4. Size of ArrayList size(): Returns the number of elements in the list.
  5. Checking if Element Exists contains(Object o): Checks if the list contains the specified element. isEmpty(): Checks if the list is empty.
  6. Iterating Over Elements For-each Loop

//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:

  • Removing duplicate elements (e.g., handling duplicate items from a list of web elements).
  • Storing unique data (e.g., storing a set of unique text values from web elements).

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:

  • Storing element locators with their actions (e.g., mapping actions like click or send keys to specific elements).
  • Mapping test data (e.g., storing expected and actual results during testing).

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:

  • Managing asynchronous tasks like handling multiple browser windows or tabs in parallel testing.
  • Storing actions to be performed on web elements in a specific order.

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:

  • Iterating over collections of web elements or test data.
  • Using for-each loop to perform actions on each element.

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:

  • Parallel testing: Managing shared resources or data across multiple threads.
  • Handling results or logs in a thread-safe manner.

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.



要查看或添加评论,请登录

Arjun K.的更多文章

  • Java OOPs...Encapsulation!

    Java OOPs...Encapsulation!

    Consider a real-life example of your bank account, your account balance is private—you wouldn’t want anyone to directly…

  • Little’s Law in Performance Testing

    Little’s Law in Performance Testing

    In 1954, John Little published a paper in which he described the queueing theory by a new law. Later, it is named…

  • Performance Metrics- Throughput, latency and response time!

    Performance Metrics- Throughput, latency and response time!

    Throughput Throughput serves as a crucial performance metric for assessing system efficiency, identifying bottlenecks…

  • Application Performance Improvement using CAST SQG formerly AIP.

    Application Performance Improvement using CAST SQG formerly AIP.

    ??What is CAST Structural Quality Gate (SQG) formerly AIP ? CAST SQG draws on CAST’s extensive experience in deep…

  • Performance Test-An Overview!

    Performance Test-An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Software Performance Test - An Overview!

    Software Performance Test - An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Compile-time & Runtime Errors in Java..

    Compile-time & Runtime Errors in Java..

    Compile-time A compile-time error in Java refers to an error that occurs during the compilation phase, when the Java…

  • Java for Everyone...Encapsulation.

    Java for Everyone...Encapsulation.

    Consider a real-life example of your bank account. Your account balance is private—you wouldn’t want anyone to directly…

  • Java for Everyone... Arrays

    Java for Everyone... Arrays

    An array is a container object that holds a fixed number of values of a single type. The length of an array is…

  • Java for Everyone... StringBuilder & StringBuffer

    Java for Everyone... StringBuilder & StringBuffer

    StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated…

社区洞察

其他会员也浏览了