I am using HtmlUnit to get an HtmlTable. I am trying to get a List of cells of each column.
So far, in the code I've tried I can find the first column. How can I iterate through each column and run some code in them?
I'd like to make sure they're all sorted alphabetically, but I just need to figure out where to place that code.
EDIT: I found my answer. I think I worded the question wrong. I needed to get each column and put them into their own collection. In the original example, I showed only column1. But I need EACH column (based upon how many cells are in each row). Below is some code that worked. But it may be able to be optimized better.
HtmlPage htmlPage = webClient.getPage("http://localhost:8080/myurl");
HtmlTable myTable = htmlPage.getHtmlElementById("mytable");
// find the number of columns by grabbing the first row and returning the number
// of cells within the first row
int numberOfColumns = myTable.getRows().stream().map(row -> row.getCells()).findFirst().get()
.size();
// initialize columns
List<List<String>> columns = new ArrayList<List<String>>(numberOfColumns);
// initialize new arraylists for each column based upon the number of columns
for (int i = 0; i < numberOfColumns; i++)
columns.add(new ArrayList<>());
// iterate through each column
for (int columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) {
// iterate through each row
for (int rowIndex = 0; rowIndex < myTable.getRows().size(); rowIndex++) {
String asText = myTable.getCellAt(rowIndex, columnIndex).asText();
columns.get(columnIndex).add(asText);
}
}
//iterate through the columns and do stuff!
columns.forEach(a -> {
//do stuff to the column such as verify it was sorted, or sort it yourself etc
System.out.println("column" + a.toString());
a.forEach(b -> {
//do stuff
LOG.info(b);
});
});