Using Java Stream API

Java 8 came up with a lot of cool features such as Stream, Lambda expressions which can help reduce your code complexity and make operations easier. One of the examples will be shared in this article which can help you implement some cool features of Java 8 in your organization.

Using Java Stream API

Stream API can come in handy if you are an automation guy and is looking to reduce some code and building new logic. Today we will focus on how to retrieve the text of the web elements using Stream API and lambda expressions. To begin with, first, we will use the old traditional way of extracting the text from web element in the code shown below -

Java 8 came with a new package called java.util.stream which consists of interfaces and classes to deal with collection and arrays in an effective way. One of the most significant interfaces in Stream API is called Stream <T> which has methods like filter(), map(), count(), distinct() which can solve complex code problems.

Consider below code first -

The above codes use 2 lists to extract the product name and iterate through each element which can effectively be minimized using Stream API. 

Let's see how same code can be optimized using Stream API library -

Stream API and Lambda expression used in Selenium Automation

That's it! Please go through the above code and try to implement it in your project. Remember, code is not important but how you implement it is important.

If we want to extract unique products, instead of using List we can use Set for the same example.

Few other terms associated with Stream API are given below -

Map()
Let's suppose we want to apply some function to the stream of elements without iteration, in that case we can use Map() function offered by Stream API. For example, there is one integer array and we want to convert it to the square of every element. int A[] = [1,2,3,4] -> [1,4,9,16].

Distinct()
As the name sounds, if we want to extract distinct elements from a stream, we can use Distinct()

Collect()
To collect the element is a different data structure, for example in List or a set.

Below is the example snippet for Map()
Map() in Stream API Java 8

Below is the example code for Distinct()
Distinct() in Stream API Java 8

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD