Bryan Noyahr
Bryan Noyahr

Reputation: 13

How can I add an array an array to this loop so I can store the data

I would like to add the data generated by (e.getText()); into an array in the following code snippet. I tried several different things, but it does not work for me. What should I replace the question mark with. Appreciate the help.

    List<WebElement> NameColumns = table.findElements(By.xpath("//tr/td[" + col_name_position + "]"));
    for (WebElement e : NameColumns) {
        String[] strArray = new String[3];
        strArray[?] = (e.getText());
        System.out.println(e.getText());
    }

Upvotes: 0

Views: 65

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19565

This conversion may be implemented using Stream:

List<WebElement> nameColumns = table.findElements(By.xpath("//tr/td[" + col_name_position + "]"));

String[] strArray = nameColumns
    .stream()                  // Stream<WebElement>
    .map(WebElement::getText)  // Stream<String> of `text` field
    .peek(System.out::println) // optional print of text for each WebElement
    .toArray(String[]::new);   // collect to string array

Upvotes: 1

Ezio
Ezio

Reputation: 2985

The string array should be declared outside of the for loop.

    List<WebElement> NameColumns = table.findElements(By.xpath("//tr/td[" + col_name_position + "]"));
    String[] strArray = new String[NameColumns.size()];
    int index = 0;
    for (WebElement e : NameColumns) {
        strArray[index++] = (e.getText());
        System.out.println(e.getText());
    }

Upvotes: 1

Related Questions