collections in java for selenium webdriver

Collections is nothing but a backpack, guess what are the things you can store in a backpack. Probably you must have guessed everything that we can store in a backpack, but let list a few of them : 1. Laptop, Mouse, HeadPhones, earPhones, Mouse (computer's and animal too), Book, Notepad, pen, pencil you can write so on.

Almost you can store everything; you cannot store an elephant though. Within the backpack's size, you can store all the things.

Let's discuss Java Collection with selenium : Collection is a framework that manipulates only one data type, which is the god data type of Java. I mean data type of Object class, I hope you know that Object class is the topmost class in java.

Collection framework mostly used along with a group of Objects rather than Objects.
Description as per Books:

Collections in java is a framework that provides an architecture to store and manipulate the group of objects. The Collection helps the user to store only the Object class type, but every single class in java is subclass to Object class, which means we can store anything with help classes present in the collection.

I am not going to discuss everything present in collection, but only collection that we use frequently and which are :

    <li">Arrays <li">List <li">Set <li">Map (map is not a collection but mostly used for collections)


Where we use collections in selenium : Whenever we deal with more than one item, then we use collections in selenium webdriver. Few places are:

  • when we try to retrieve the more than one match of elements
  • when we handle multiple tabs/windows
  • When we retrieve option from the dropdown using getOptions() method

how to use arraylist in selenium webdriver

As per my knowledge, we do not use ArrayList in selenium, but we do use List. People prefer List over ArrayList because when you use a List, you can store a different kind of list categories like ArrayList, LinkedList, TreeList so on. But when we use ArrayList, then we can only store only the ArrayList type.

This is the primary reason why the findElements method returns List(broad) rather than ArrayList(narrow).

list-of-webelements

Now if you are like me then you get this doubt, why cannot I use ArrayList for it instead of List.

arraylist-selenium-collections

So we have to store the value based on the return type only, so when you should store the list of web elements using List only.

But I did not mean that we cannot store the list of web elements in ArrayList, but it is not recommended. If you think who cares about the recommendation, then you got to downcast the returned values to store it in ArrayList with selenium.

ArrayList<WebElement> al =
	(ArrayList<WebElement>) driver.findElements(By.xpath("//input"));


how to print a list of web elements in selenium : Sometimes people tend to ask how can we print a list of web elements in interviews, The answer is simple Loop over the collection using the for each loop or for loop then use System.out.println.

But the thing is, it does not make any sense to print a web element; the questions always try to mean how do you print some attributes of web element. So while iterating and printing, print something useful like text, attributes, or cssValues

how to store values in the array in selenium webdriver

We can store values in lists if we want, but it is better to use ArrayList rather than Arrays, ArrayList is an extension of Arrays except that ArrayList can grow without limit.

We can store things on arrays only when their return type is an array; otherwise, prefer ArrayList. Let's see the situation when we use Arrays in selenium.

For example, if we want to verify a value by splitting the string output, then splitting always returns an Array of values., there values will be substrings.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestDrpdownSorted {
	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "D:PATHchromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.get("https://chercher.tech");
		String[] vals = driver.getTitle().split(" ");
		for (String str : vals) {
			System.out.println(str);
		}
    }
}

arrays-with-selenium

foreach in selenium webdriver

For-each is one of the ways to traverse the Collection in java, this is like for loop, while loop, do-while loop. But it does not have any control variables or conditions in the loop. It will pick one by one element from the Collection and brings to use.

We use the for-each loop in selenium to iterate over a list of web elements (when used findElements), set of Window handles, options present in dropdowns.

Few things to remember about for each loop:

  • It starts with the keyword for like a normal for-loop.
  • Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  • In the loop body, you can use the loop variable you created rather than using an indexed array element.
  • It's commonly used to iterate over an array or a Collections class (e.g., ArrayList, HashSet)
  • You might need to declare a variable outside the loop if you want to terminate the loop after some iterations
for (typeOfIndividuelItem item : collectionOfIterms)
{
    //statements using item;
}
public static void main(String[] args) {
	System.setProperty("webdriver.chrome.driver", "D:PATHchromedriver.exe");
	WebDriver driver = new ChromeDriver();
	driver.get("https://chercher.tech");
	List eles = driver.findElements(By.xpath("//someValue"));
	for (WebElement element : eles) {
		System.out.println(element.getText());
	}
}

how to use Set in selenium webdriver

Java Set is a collection of objects that allows no duplicate elements to be stored. Java Set is an interface that extends the Collection interface.

Unlike List, Java Set is NOT an ordered collection; its elements does NOT have a particular order. Java Set does NOT provide control over the position where you can insert an element. You cannot access elements by their index and also search elements in the list.

Set is used when we are dealing with a unique element or values like window handles, getWindowHandles()returns set of String

// get the All the session id of the browsers
Set allGUID = driver.getWindowHandles();

how to use the Map in selenium

We can use Maps or hashMaps in selenium when we want to read key-pair values; For example, when we read data from the properties files or JSON file, we would be using HashMaps along with Selenium.

Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to perform lookups by keys or when someone wants to retrieve and update elements by keys.

Some examples are:

  • A map of error codes and their descriptions.
  • A map of zip codes and cities.
  • A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
  • A map of classes and students. Each class (key) is associated with a list of students (value).

I have never used a hash table with selenium so far, so if you ever used, let me know in the comment section.

// PLEASE DO WRITE IMPORT STATEMENTS
public class ReadMultiplePropertiesFiles {
	public static void main(String[] args) throws IOException {
		// create file input stream object for the properties file
		FileInputStream fis = new FileInputStream("C:pathlogin.properties");
		FileInputStream fis2 = new FileInputStream("C:pathconfig.txt");
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		prop.load(fis);
		//load all the files
		prop.load(fis2);
		// get the property of "url" using getProperty()
		System.out.println(prop.getProperty("url"));
	}
}

selenium collections interview questions

I have not provided an answer to the questions because I want you guys to think

  • Why we get a List of web elements rather than Set of Webelements ?
  • Where do you see the list is being used in selenium. ?
  • Why is Set returned when we get window handles ?
  • Can we replace set with List in selenium ?
  • Where do we use the map in Selenium ?
  • How do we handle tables in selenium ?
  • Why Is List returned instead of ArrayList in findElements ?
  • What is the return type of getOptions() method in dropdowns
  • Why cannot we use an Array instead of an ArrayList?
  • Convert a list of values into a set of values?
  • What is the concept behind keys in Maps?
  • What is the concept behind values in Maps?
  • What is Iterator?
  • What is the list Iterator?
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Mani
    List we used in webdriver because list can have reparative elements list element does not have to be key value Fashion. 
    Set has to be accepting values only in key,value form which is nontepeatative so that's why we donot use set and used list .
    Always the locators value is either identified as I'd or name tag not in key value manner.
    
    Reply
  • Please provide the answers for the above questions
    Reply