Usage of Java Stream API in Selenium – Retrieving Unique Text From a List Of WebElements

In previous post, we learnt to Retrieve text from a list of web elements using Java Stream APIs.

You may require just to retrieve unique text only. We used a List in previous post which allows duplicates. We can just use a Set to avoid duplicates.

Java Code:-

package RealtimeValdationAutomationTesting;

import java.util.HashSet;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;



import io.github.bonigarcia.wdm.WebDriverManager;

public class RetrieveUniqueTextFromListOfElementUsingStreamAPICollect {
	
	@Test
	public void RetrieveTextFromListOfElementWithStremAPI()
	{
		// Auto setup of chrome executable file
		WebDriverManager.chromedriver().setup();
		
		// Launching browser
		WebDriver driver = new ChromeDriver();
		
		// Load the URL
		driver.get("http://automationpractice.com/index.php");
		
		// Creating a Set to store only unique names
		Set uniqueProductName = new HashSet();
		
		// Locating all product names at home page
		
		driver.findElements(By.xpath("//ul[contains(@class,'active')]//a[@class='product-name']"))
		.stream()
		.forEach(product -> uniqueProductName.add(product.getText()));
		
		// Print count of product found
		System.out.println("Total unique product found : "+uniqueProductName.size());
		
		// Printing product names
		System.out.println("All product names are : ");
		uniqueProductName.forEach(name -> System.out.println(name));
		
		
		// closing the browser
		driver.quit();
	}
	
	
	

}

Output:-

Total unique product found : 5
All product names are : 
Printed Dress
Blouse
Printed Chiffon Dress
Faded Short Sleeve T-shirts
Printed Summer Dress

You must be thinking why a separate post just to say use Set for unique elements. Anyone can think the same. Yes you are correct but here I am going to show you usage of some other aggregate functions of stream APIs.

map():

There is another method in Stream api named “map()”. It returns a stream consisting of the results of applying the given function to the elements of this stream. For example:- Suppose I have an array of int and I want to get square of each element of array. e.g. [1,2,3,4] => [1,4,9,16]. We can achieve the same without iterating explicitly using map.

distinct():-

It returns a stream consisting of the distinct elements of this stream. You can remove duplicates from a source using this method.

collect() :-

It is a terminal operation. We can retrieve the final stream in to a list or a set.

I will show usage of each method in below Selenium script:-

package RealtimeValdationAutomationTesting;

import java.util.Set;
import java.util.stream.Collectors;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;



import io.github.bonigarcia.wdm.WebDriverManager;

public class RetrieveUniqueTextFromListOfElementUsingStreamAPICollect {
	
	@Test
	public void RetrieveTextFromListOfElementWithStremAPI()
	{
		// Auto setup of chrome executable file
		WebDriverManager.chromedriver().setup();
		
		// Launching browser
		WebDriver driver = new ChromeDriver();
		
		// Load the URL
		driver.get("http://automationpractice.com/index.php");
		
		
		// Locating all product names at home page
		/*
		 * map() is used to replace stream with text. If stream consists of {webelement1, webelement2},
		 * after map operation it will be their inner text {textOfWebelement1, textOfWebElement2}.
		 * Using collect() method to store resultant stream to a set directly to remove duplicates. 
		 */
		Set uniqueProductNames = driver.findElements(By.xpath("//ul[contains(@class,'active')]//a[@class='product-name']"))
		.stream()
		.map(productWebElement -> productWebElement.getText())
		.collect(Collectors.toSet());
		
		// Print count of product found
		System.out.println("Total unique product found : "+uniqueProductNames.size());
		
		// Printing product names
		System.out.println("All product names are : ");
		uniqueProductNames.forEach(name -> System.out.println(name));
		
		
		// closing the browser
		driver.quit();
	}
	
	
	

}

Using distinct():-

package RealtimeValdationAutomationTesting;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;



import io.github.bonigarcia.wdm.WebDriverManager;

public class RetrieveUniqueTextFromListOfElementUsingStreamAPICollect {
	
	@Test
	public void RetrieveTextFromListOfElementWithStremAPI()
	{
		// Auto setup of chrome executable file
		WebDriverManager.chromedriver().setup();
		
		// Launching browser
		WebDriver driver = new ChromeDriver();
		
		// Load the URL
		driver.get("http://automationpractice.com/index.php");
		
		
		// Locating all product names at home page
		/*
		 * map() is used to replace stream with text. If stream consists of {webelement1, webelement2},
		 * after map operation it will be their inner text {textOfWebelement1, textOfWebElement2}.
		 * distinct() will remove all duplicates
		 * Using collect() method to store resultant stream to a list. 
		 */
		List uniqueProductNames = driver.findElements(By.xpath("//ul[contains(@class,'active')]//a[@class='product-name']"))
		.stream()
		.map(productWebElement -> productWebElement.getText())
		.distinct()
		.collect(Collectors.toList());
		
		// Print count of product found
		System.out.println("Total unique product found : "+uniqueProductNames.size());
		
		// Printing product names
		System.out.println("All product names are : ");
		uniqueProductNames.forEach(name -> System.out.println(name));
		
		
		// closing the browser
		driver.quit();
	}
	
	
	

}

Output:-

Total unique product found : 5
All product names are : 
Faded Short Sleeve T-shirts
Blouse
Printed Dress
Printed Summer Dress
Printed Chiffon Dress

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

Leave a Reply

Your email address will not be published. Required fields are marked *