Make Selenium Easy

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

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 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:-


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.


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

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

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “Usage of Java Stream API in Selenium – Retrieving Text From a List Of WebElements

  1. ordering of tutorials is very confusing, from Rest API we moved suddenly to Selenium. Can we please have indexes

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.