Tutorial 12 – Usage of lambda function, Stream/filter, last count in Selenide
What you will Learn in this blog:
Usage of lambda function
Usage of Stream and filter
Usage of last count
Code snippet
Usage of lambda function
In the last blog we had seen how to print the element’s text and ‘href’ using a ‘for’ loop
Let us see how to get the same information using a lambda function.
Note: Lambda functions, unlike methods, do not need a name. Lambda function can be implemented right in the body of a method.
The highlighted section below is a lambda expression
Execute, notice below that text of each element (including all the courses) is printed
Similarly, we can append the ‘href’ attribute
Usage of Stream and filter
If you notice the console output, there is lot of white space. We can remove or filter this white space using streams
The below syntax will serve the purpose. We are filtering the empty text and ignoring it. We are then sending this filtered data to ‘foreach’ block
So we have
Execute. Notice below that white space is no more
Usage of last count
Let us say we want to print the text of only last 5 courses
To achieve this, we can use ‘last()’ method as shown below
Execute, notice below that the text of last 5 links gets printed in console
Code snippet
package w2a.selenide;
import static com.codeborne.selenide.Selenide.$$;
import static com.codeborne.selenide.Selenide.open;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.ElementsCollection;
public class ElementsTest {
@Test
public void searchTest() throws InterruptedException, MalformedURLException {
Configuration.browser = "firefox";
open("https://www.selenium-tutorial.com/courses");
ElementsCollection counts = $$(By.tagName("a"));
/*
//lambda expression
counts.forEach(l -> System.out.println(l.getText()));
counts.forEach(l -> System.out.println(l.getText()+ "########" + l.getAttribute("href")));
//stream/filter
counts.stream().filter(f -> !f.getText().isEmpty()).forEach(f -> System.out.println(f.getText()));
*/
//last count
counts.last(5).forEach(l -> System.out.println(l.getText()));
Thread.sleep(5000);
}
}
Thank you for reading!