DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Understanding Lazy Evaluation in Java Streams

Trending

  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Ethical AI in Agile
  1. DZone
  2. Coding
  3. Java
  4. Usage of Java Streams and Lambdas in Selenium WebDriver

Usage of Java Streams and Lambdas in Selenium WebDriver

In this tutorial, get a glimpse of applications of Java Lambdas and Streams in Selenium to simplify the WebDriver code.

By 
Aswani Kumar Avilala user avatar
Aswani Kumar Avilala
DZone Core CORE ·
Updated May. 04, 22 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
16.0K Views

Join the DZone community and get the full member experience.

Join For Free

Lambda and Selenium logos

Overview: Java Streams and Lambdas

Lambdas

A lambda expression is a microcode that takes in parameter(s) and returns a value. Lambda expressions are similar to methods, but they are anonymous and they can be implemented right in the body of a method.

Lambdas Syntax

Java
 
parameter -> expression //to use single parameter & expression
(parameter1, parameter2) -> expression //to use multiple parameters & expression
(parameter1, parameter2) -> {code block} //to use multiple parameters & conditions, loops and more complex logic


Streams

A stream of objects supports both sequential and parallel aggregate operations. Examples include finding the max or min element and finding the first element matching the giving criteria in a declarative way similar to SQL statements used in SELECT queries.

Streams Syntax

Java
 
List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);


Implementation of Java Streams and Lambdas in Selenium WebDriver

Java Lambdas and Streams simplify the Selenium WebDriver code, especially when you are working with web tables, handling windows/frames, sorting the list of web elements, or filtering the web elements from the collection.

Steps for Implementation

Step 1:

Create a Maven Java project to get started with the implementation of Java Streams and Lambdas in Selenium WebDriver. Search for dependencies such as Selenium Java, WebDriver Manager, and TestNG from the Maven repository location https://mvnrepository.com/ and add to pom.xml as shown below.

Searching for dependencies

Step 2:

Create a TestNG class and add the below test methods.

Scenario 1:

The below test method will find out the list of all the hyperlinks from the demowebshop page and then filter out the links which are having only Linktext.

Java
 
	@Test(description = "Test to filter links from the web page")
	public void tc1_filter_links() {
		WebDriverManager.chromedriver().setup();
		WebDriver driver=new ChromeDriver();

		driver.get("http://demowebshop.tricentis.com");
		List<WebElement> links=driver.findElements(By.tagName("a"));
		System.out.println("No of Links :"+links.size());
		//Below Code is using Lambdas & Streams
		List<String> filterlinks=links.stream().filter(ele->!ele.getText().equals("")).map(ele->ele.getText()).collect(Collectors.toList());
		System.out.println("After Applying Filter, Links having only Linktext :"+filterlinks.size());
		filterlinks.forEach(System.out::println);
		driver.close();
	}


Expected Output on Console: 

  • No of Links: 95
  • After Applying Filter, Links having only Linktext: 66

Scenario 2: 

The below test method will filter the products by prices from the list of having greater than $1000 from the home page of the demowebshop.

Java
 
	@Test(description ="Test to filter the products which are >1000")
	public void tc2_filter_price()
	{
		WebDriverManager.chromedriver().setup();
		WebDriver driver=new ChromeDriver();
		driver.get("http://demowebshop.tricentis.com/");


		List<WebElement> prodTitles=driver.findElements(By.xpath("//h2[@class='product-title']"));
		List<WebElement> prodPrices=driver.findElements(By.xpath("//div[@class='prices']"));

		Map <String,Double>products_map=new HashMap<String,Double>();
		
		for(int i=0;i<prodTitles.size();i++) 
		{
			String title=prodTitles.get(i).getText();
			double price=Double.parseDouble(prodPrices.get(i).getText());

			products_map.put(title, price);

		}
		//Below Code is using Lambdas & Streams	
		//find product whose price is greater than 1000 (Process using filter)
		System.out.println("**** Product price is > 1000 using filter & lambda ****");
		System.out.println("**** Below Products price is > 1000                ****");
                products_map.entrySet().stream().filter( e -> e.getValue() > 1000).forEach(v->System.out.println(v));
		driver.close();
    }


Expected Output on Console:

  • Product price is > 1000 using filter & lambda
  • Below Products price is > 1000
  • Build your own expensive computer=1800.0
  • Build your own computer=1200.0
  • 14.1-inch Laptop=1590.0

Scenario 3: 

The below test method will make the product list sorted by A-Z.

Java
 
	@Test(description = "Test to make the products in Sorted Order A-Z")
	public void tc3_sorted_list()
	{
		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();

		driver.get("http://demowebshop.tricentis.com/");
		driver.findElement(By.xpath("//ul[@class='top-menu']//a[normalize-space()='Books']")).click();

		Select sortbydrp=new Select(driver.findElement(By.id("products-orderby")));
		sortbydrp.selectByVisibleText("Name: Z to A");
		
		List<WebElement> product_items=driver.findElements(By.xpath("//h2[@class='product-title']"));
		List<String> beforesort=product_items.stream().map(item->item.getText()).collect(Collectors.toList());
		System.out.println("Before Sort : " +beforesort);
		List<String> aftersort=product_items.stream().map(item->item.getText()).sorted().collect(Collectors.toList());
		System.out.println("After Sort : "+aftersort);
		driver.close();
	}


Expected Output on Console:

  • Before sort: [Science, Health Book, Fiction EX, Fiction, Copy of Computing and Internet EX, Computing and Internet]
  • After sort: [Computing and Internet, Copy of Computing and Internet EX, Fiction, Fiction EX, Health Book, Science]

Scenario 4: 

The below test method will handle switching to Windows.

Java
 
@Test(description = "Test to Handle Windows")
	public void tc4_handle_windows()
	{
		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();
		driver.get("https://demoqa.com/browser-windows");
		driver.findElement(By.id("tabButton")).click();
		
		Set<String>windowIds=driver.getWindowHandles(); // Here using Set collection
		//Print the url's using lambda expression
		windowIds.forEach(winid -> System.out.println(driver.switchTo().window(winid).getCurrentUrl()));
		driver.close();
    }


Expected Output on Console:

  • https://demoqa.com/browser-windows
  • https://demoqa.com/sample

Conclusion 

The above is a glimpse of the applications of Java Lambdas and Streams in Selenium to simplify the WebDriver code. The above test methods are some of the common scenarios used in the automation of web applications using Selenium WebDriver API, but not limited to these. Java Lambdas and Streams can be used in any kind of scenario on web tables, handling windows/frames, sorting the list of web elements, or filtering the web elements from a collection.

Java (programming language) Stream (computing) Selenium

Opinions expressed by DZone contributors are their own.

Related

  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Understanding Lazy Evaluation in Java Streams

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!