Using Java8 Concepts with Selenium WebDriver
Applying Java8 streams concepts to optimize our code
- Lets understand on sorting. Using java8 streams concept we will check if values in a list are sorted or not.
The approach will be , first we will get the text of list of webelement and then on this list we will apply sorted method of Java8.Sorted method arranges all the values in ascending order.
List<WebElement> elementlist=driver.findElements(By.xpath("//ul//li"));List<String>originallist=elementlist.stream().map(e->e.getText()).collect(Collectors.tolist());List<WebElement> Sortedlist=originallist.stream().sorted().collect(Collectors.tolist());Assert.assertTrue(originallist.equals(Sortedlist));
The above assertion statement will return true if values are sorted, else it will return false.
2. Handling autosuggestive textbox using Java8 streams concept in Selenium
driver.findElements(By.xpath("//ul[@id='ui-id-1']/li/div")).stream().filter(p->p.getText().contains("Kingdom")).findFirst().ifPresent(p->p.click());
Filter- This accepts predicate functional interface and return a boolean value. In general terms this behaves like a if condition
Approach here will be , get the text of list of webElement and apply a filter condition to check for a text using contains method. findFirst method checks for a filtered value and ifPresent is used to perform required action on filtered text.
3. Clicking on all the checkboxes using Java8 foreach method.
List<WebElement> checkboxes=driver.findElements(By.xpath("//input[@class='checkbox']"));checkboxes.stream().forEach(ele->ele.click());
In the above code,foreach method is used to perform click operation on each checkbox.