sreenath sreenath - 7 months ago 296
Java Question

How to check webelements in webtable is sorted alphabetcally or not?(using selenium webdriver)

Our application contains table of web elements,so my aim is to check whether the contents table is alphabetically ordered or not....

WebDriver d=new FirefoxDriver();
d.get("http://www.javatpoint.com/wrapper-class-in-java");

WebElement table=d.findElement(By.xpath(".//*[@id='city']/table/tbody"));
List<WebElement> lst=table.findElements(By.tagName("tr"));
System.out.println(lst);

List ls=new ArrayList<String>();
for(int i=0;i<=6;i++)
{
ls=lst.addAll(get(i).getText())

}


My aim is to store string type webelement in one list and create another list which is of sorted kind
in the end compare two list...please help?

Answer

You can store the default sorting in a string array like obtainedList and then sort it using collections for sortedList and lastly both.

ArrayList<String> obtainedList = new ArrayList<>(); 
List<WebElement> elementList= driver.findElements(By.xpath(YourLocator));
for(webElement we:elementList){
   obtainedList.add(we.getText);
}
ArrayList<String> sortedList = new ArrayList<>();   
for(String s:obtainedList){
sortedList.add(s);
}
Collections.sort(sortedList);
Assert.assertTrue(sortedList.equals(obtainedList));

For descending order add:

Collections.reverse(sortedList);

after Collections.sort(sortedList);