How to compare values from the list or from dropdown list in webdriver (Java)?

First create a list of your expected items and then retrieve the list of all items in the dropdown and store them in a list. Now you can compare these two lists by using the following code.


        String[] exp = {"Month", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
        List<String> expList = new ArrayList<String>();
        
        for(int i=0;i<exp.length;i++){
            expList.add(exp[i]);
        }
        
        List<String> actList = new ArrayList<String>();
        Select se = new Select(driver.findElement(By.id("date_mon")));
        
        List<WebElement> options = se.getOptions();
        
        for(WebElement dd : options){
            actList.add(dd.getText());
        }    


//call the below method to compare to lists

    public void compareDropdown(List<String> expList,List<String> actList){
        //sorts both lists
        Collections.sort(expList);
        Collections.sort(actList);
        //first compares the size of both list, if true then compares each item in order,if false skips and display both are not same
        if(expList.size()==actList.size()){
            for(int i=0;i<expList.size();i++){
                //comparing each item in order
                if(expList.get(i).equals(actList.get(i))){
                    System.out.println("Matched");
                }else{
                    System.out.println("Not matched");
                }
            }
        }else{
            System.out.println("Drop down values are not same in number");



-------------------------------------------------------------------------------------------------------------------------------------------------------------

verifying drop down values using WebDriver


public boolean checkOptions(String[] expected){
    WebElement select = driver.findElement(By.id("ctl00_cphMainContent_dq14_response"));
    List<WebElement> options = select.findElement(By.xpath(".//option"));
    int k = 0;
    for (WebElement opt : options){
        if (!opt.getText().equals(expected[k]){
            return false;
        }
        k = k + 1;
    }
    return true;

public List<String> getList() {
  List<String> element = new ArrayList<>();
  element.add("1");
  element.add("2");
  return element;
 }

 
 public void enteryOptionsInDropdown(){
  driver.findElement(By.xpath("//select[@id='day']")).click();
  for (String text : getList()) {
   String xpath = "//select[@id='day']/option[text()='%s']";
   xpath = xpath.replaceFirst("%s", text);
   String text2 = driver.findElement(By.xpath(xpath)).getText();
   if (text2.equalsIgnoreCase(text)) {
    System.out.println("Element exists" + text2);
   } else {
    System.out.println("Element do not exist" + text2);
   }

  }
 }


About Me

My photo
Pune, Maharastra, India
You can reach me out at : jimmiamrit@gmail.com