How to convert a list of webelement to another list in the form of string?

15,005

Solution 1

You can do something like this:

List<WebElement> lst=d.findElements(By.tagName("a"));
List<String> strings = new ArrayList<String>();
for(WebElement e : lst){
    strings.add(e.getText());
}

Solution 2

First, you should create an instance of List<String>:

List<String> lst1 = new ArrayList<>();

Then just get an element (lst.get(k).getText()) from lst and add it to lst1 in the loop.

for(int i = 0; i < lst.size(); ++i) lst1.add(lst.get(i).getText());

Or use the lovely way with Stream API:

lst.stream().map(WebElement::getText).forEach(lst1::add);
Share:
15,005
sreenath
Author by

sreenath

Updated on June 04, 2022

Comments

  • sreenath
    sreenath almost 2 years

    my code is:

    public static void main(String[] args) {
        WebDriver d=new FirefoxDriver();
        d.get("https://bbc.com");   
        List<WebElement> lst=d.findElements(By.tagName("a"));   
        for(int k=0;k<=lst.size();k++)
            List<String> lst1=lst.add(get(k).getText());
    }
    

    my aim is to import all text formated webelement to lst1

  • sreenath
    sreenath about 8 years
    after that i want to sorted the list....so i used Collections.sort(lst1); System.out.println(lst1); ...but it showing some error
  • Titus
    Titus about 8 years
    The loop will generate a IndexOutOfBoundsException because of the condition k <= lst.size(), it should be k < lst.size()