DataTable to list of maps

Viewed 55

I have this kind of a table to deal with:

enter image description here

The path for the headers is:

List<WebElement> headers;
       headers = driver.findElements(By.xpath("//*[@id=\"table1\"]/thead/tr/th"));

The path for the table body is:

 List<WebElement> dataTable;
       dataTable = driver.findElements(By.xpath("//*[@id=\"table1\"]/tbody/tr/td"));

List of headers has size of 6, list of dataTable has size of 24.

I am trying to put this to a list of maps

List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();

So far I've managed to add just the first entry:

for (int i = 0; i < headers.size(); i++) {
        mapa.put(headers.get(i).getText(), dataTable.get(i).getText());
    }

and the output is:

{Last Name=Smith, First Name=John, Email=jsmith@gmail.com, Due=$50.00, Web Site=http://www.jsmith.com, Action=edit delete}

But if I put it to the loop where row size = 4, it will give me a list of 4 same maps. What do I have to do to make it work? I would like to have that kind of format (list of maps) so I can send it as a JSON in API POST testing.

Thank you for your help!

1 Answers

Example input

class WebElement {
    private final String text;
    
    public WebElement(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}
List<WebElement> header = List.of(
    new WebElement("Last Name"),
    new WebElement("Name"),
    new WebElement("Email"),
    new WebElement("Due"),
    new WebElement("Web Site"),
    new WebElement("Action")
);
List<WebElement> dataTable = List.of(
    new WebElement("Smith"),
    new WebElement("John"),
    new WebElement("jsmith@gmail.com"),
    new WebElement("$50.00"),
    new WebElement("http://www.jsmith.com"),
    new WebElement("edit delete"),
    new WebElement("Pippo"),
    new WebElement("Pluto"),
    new WebElement("pippo.pluto@gmail.com"),
    new WebElement("$40"),
    new WebElement("http:pippo.com"),
    new WebElement("edit"),
    new WebElement("Ciao"),
    new WebElement("Adam"),
    new WebElement("adam.ciao@gmail.com"),
    new WebElement("$60"),
    new WebElement("http://ciao.com"),
    new WebElement("delete")
);

List<Map<String, String>> listOfMaps = new ArrayList<>();
for(int i = 0; i < dataTable.size(); i = i + header.size()) {
    Map<String, String> mapa = new HashMap<>();
    for(int j = 0; j < header.size(); j++) {
        mapa.put(header.get(j).getText(), dataTable.get(i + j).getText());
    }
    listOfMaps.add(mapa);
}

Example output:

listOfMaps.forEach(map -> System.out.println(map));
{Action=edit delete, Email=jsmith@gmail.com, Web Site=http://www.jsmith.com, Due=$50.00, Last Name=Smith, Name=John}
{Action=edit, Email=pippo.pluto@gmail.com, Web Site=http:pippo.com, Due=$40, Last Name=Pippo, Name=Pluto}
{Action=delete, Email=adam.ciao@gmail.com, Web Site=http://ciao.com, Due=$60, Last Name=Ciao, Name=Adam}

Related