Stream API is the major feature introduced in Java 8. As an automation tester, if you think you don’t have to learn about it, you may be wrong. Yes you don’t need to know everything but little basic knowledge of Stream API will help you to reduce lines of code in Selenium script.

I am starting a series of posts on Usage of Java Stream API in Selenium. In this post, we will see how Stream API can help you to retrieve the text of a List of WebElements quickly.

Introduction of Java Stream API :-

Java 8 provided a new package called java.util.stream which contains multiple classes and interfaces which helps you to get sequence of data from a Collection or array and apply aggregate operation on those elements.

A generic interface named Stream<T> is a major interface in stream package of Java. It provides a sequence of elements supporting sequential and parallel aggregate operations. It contains a lot of methods like map(), count(), distinct(), filter() etc which makes complex operation on elements easier.

Let’s see the usage in a scenario with Selenium:-

We need to locate and print the names of all clothes present at home page of a shopping site. Let’s do the same thing using traditional way first:-

Without using stream API:-

Output:-

Using Java Stream API:-

Above , we first stored the found web elements in to a list and then iterated. Using stream we do not need to save it. We just need text from each webelement not web elements. We can get stream of web elements using stream() method. Once we get it, we apply logic to retrieve and add text from each web element in to resultant list in forEach() method. I am using lambda expression in forEach() method.

Output:-

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.

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply