how to validate a list of strings are in alphabeti

2020-04-29 02:13发布

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

标签: java selenium
2条回答
2楼-- · 2020-04-29 02:20

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);
查看更多
▲ chillily
3楼-- · 2020-04-29 02:44

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

查看更多
登录 后发表回答