Rahul
Rahul

Reputation: 759

Split and store all the last elements into an array

I wanted to store the string values retrieved into an array or list and then sort them.I have tried many ways to store them in the said manner.But nothing is helpful. can someone please help me in this regard.

List<WebElement> list = webDriver.findElements(By.xpath(expression));
int listcount = list.size();    
List optionsList = null;
String options[] = new String[listcount];

for (int i=1; i<=listcount; i++) {                     
    options[i-1] = webDriver.findElement(By.xpath("expression")).getText();
    //contains three words eg: Test Engineer Madhu               
    String[] expectedOptions = options[i-1].split(" ");
    //splitting based on the space           
    String lastName =expectedOptions[expectedOptions.length-1]; 
    //taking the lastName.
    List<String> strArray = new ArrayList<String>();
    for (int k = 0; k < i; k++) {
       strArray.add(lastName);        
    }
    optionsList = Arrays.asList(lastName);
}          
System.out.println(optionsList);
//This always results in last option's last name eg: [Madhu]
}      

Now, I want all the last Names to be stored in an array to verify if they are in sorted order or not.

Upvotes: 2

Views: 1778

Answers (2)

Paras
Paras

Reputation: 3235

You can modify your code like:

for (int i=1; i<=listcount; i++) {  
        //contains three words eg: Test Engineer Madhu               
        String[] expectedOptions = options[i-1].split(" ");
        //splitting based on the space           
        String lastName =expectedOptions[expectedOptions.length-1]; 
        //taking the lastName.
        options[i - 1] = lastName;
    }
    optionsList = Arrays.asList(options); 
    System.out.println(optionsList);

Hope it helps.

Upvotes: 0

Harbeer Kadian
Harbeer Kadian

Reputation: 394

Here is the modified code to get all the last names in a array

List<WebElement> list = webDriver.findElements(By.xpath(expression));
int listcount = list.size();    
List optionsList = null;
String options[] = new String[listcount];

for (int i=1; i<=listcount; i++) 
{                     
    options[i-1] = webDriver.findElement(By.xpath("expression")).getText();
    //contains three words eg: Test Engineer Madhu               
    String[] expectedOptions = options[i-1].split(" ");
    //splitting based on the space           
    // I hope the next line gives you the correct lastName
    String lastName =expectedOptions[expectedOptions.length-1]; 
    // lets store the last name in the array
    options[i-1] = lastName;        
 }         
 optionsList = Arrays.asList(options);
 // Iterate through the list to see all last names.

Upvotes: 1

Related Questions