Join us on :

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 backpack, but let list 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 elephant though. Within the backpack's size you can store all the things.

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

Collection framework mostly used along with 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. 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 :

  • Arrays
  • List
  • Set
  • 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 different kind of list categories like, ArrayList, LinkedList, TreeList so on. But when we use ArrayList then we can only store only ArrayList type.

This is the major reason why why findElements methods 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 recommendation, then you got to downcast the retuned values to store it in ArrayList with selenium.


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


how to print a list of webelements in selenium : Sometimes people tend to ask how can we print 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 an webelement, the questions always tries to mean how do you print some attribute of webelement. So while iterating and printing, print something useful like text, attributes, or cssValues

how to store values in 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 extension of Arrays except that ArrayList can grow without limit.

We can store things on arrays only when their return type is array otherwise prefer ArrayList. Lets see situation when we use Arrays in selenium.

For example, if we want to verify a value by splitting the string output then splitting always return 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:\\PATH\\chromedriver.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 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 (eg, 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:\\PATH\\chromedriver.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 Collection interface.

Unlike List, Java Set is NOT an ordered collection, it’s elements does NOT have a particular order. Java Set does NOT provide a 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 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 map in selenium webdriver

We can use Maps or hashMaps in selenium when we watch 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 an hash table with selenium so far, so if you ever used let me know in 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:\\path\\login.properties");
		FileInputStream fis2 = new FileInputStream("C:\\path\\config.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 answer for the questions because I want you guys to think

  • Why we get List of webelements rather than Set of Webelements ?
  • Where do you see list is being used in selenium. ?
  • Why Set is return when we get window handles ?
  • Can we replace set with List in selenium ?
  • Where do we use map in Selenium ?
  • How do we handle tables in selenium ?
  • Why List is returned instead of ArrayList in findElements ?
  • What is the rerun type of getOptions() method in dropdowns
  • Why cannot we use array instead of Array ?
  • Convert list of values into set of values ?
  • What is the concept behind keys in Maps ?
  • What is the concept behind values in Maps ?
  • What is Iterator ?
  • What is list Iterator ?

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

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