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);
Author by
sreenath
Updated on June 04, 2022Comments
-
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 about 8 yearsafter that i want to sorted the list....so i used Collections.sort(lst1); System.out.println(lst1); ...but it showing some error
-
Titus about 8 yearsThe loop will generate a
IndexOutOfBoundsException
because of the conditionk <= lst.size()
, it should bek < lst.size()