2

Is anybody know how to validate a list of strings are in alphabetical order or not using java. I tried with compareTo() but I didn't get it.

* **It is only for the validation of String. If yes to print "List is in Alphabetical order" and No, to print "Not in order"

Here is the code:::

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class ValidationOfSelectDropDown_4 {

public static void main(String[] args) throws InterruptedException {

    WebDriver driver=new FirefoxDriver();
    driver.get("http://my.naukri.com/manager/createacc2.php?othersrcp=16201&err=1");
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().window().maximize();

    WebElement single=driver.findElement(By.xpath("//select[@id='ugcourse']"));
    Select dd=new Select(single);

    String str=single.getText();
    System.out.println(str);

    }}

O/p of the String str is :

Select

Not Pursuing Graduation

B.A

B.Arch

BCA

B.B.A

...Up to end of the option

Chanakya
  • 211
  • 3
  • 11
  • 1
    You can make the problem simpler: if you already know how to get a list of strings from webdriver, the question is then "is a list of strings in order", and the webdriver part is irrelevant. – Andy Turner Nov 23 '15 at 11:13

2 Answers2

2

If you already know how to get the list of strings from webdriver (which it looks like you do), you can check the ordering of the list by comparing each element to the previous one:

if (!strings.isEmpty()) {
  Iterator<String> it = strings.iterator();
  String prev = it.next();
  while (it.hasNext()) {
    String next = it.next();
    if (prev.compareTo(next) > 0) {
      return false;
    }
    prev = next;
  }
}
return true;

If the list is small and memory is no concern, you can alternatively sort the list and compare the lists:

List<String> ordered = new ArrayList<>(strings);
Collections.sort(ordered);
boolean inOrder = ordered.equals(strings);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

What you want to do is put all those values in a ArrayList and check if tha list is sorted. So depending on how those values are separated (I'm assuming they're separated by new lines based on the example you've given), just do:

List<String> listOfValues = str.split("\n");

Then check if tha list is ordered through Guava's Ordering methods:

boolean sorted = Ordering.natural().isOrdered(list);

Then output based on sorted's value.

NB : this post is an aggregation from answers https://stackoverflow.com/a/3481842/2112089 and https://stackoverflow.com/a/3047142/2112089

Community
  • 1
  • 1
Pascal
  • 259
  • 1
  • 11
  • 27