sreenath
sreenath

Reputation: 21

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

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

Upvotes: 1

Views: 20043

Answers (3)

cagoscra
cagoscra

Reputation: 17

This is another way to do the same

List<WebElement> lst=driver.findElements(By.tagName("a"));
List<String> strings = new ArrayList<>();
lst.forEach(variable -> strings.add(variable.getText()));

Arrow operator also rocks!

Upvotes: 0

Andrew
Andrew

Reputation: 49606

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);

Upvotes: 2

Titus
Titus

Reputation: 22474

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());
}

Upvotes: 3

Related Questions