在我的Java8流中查找表中的每一列
我正在使用HtmlUnit
获取HtmlTable
。我正在尝试获取每列的单元格列表
到目前为止,在我尝试的代码中,我可以找到第一列。如何遍历每一列并在其中运行一些代码
我想确定它们都是按字母顺序排列的,但我只需要找出代码的位置
编辑:我找到了答案。我想我把问题写错了。我需要得到每一个专栏,把它们放进自己的收藏中。在最初的示例中,我只显示了第1列。但我需要每一列(基于每行中有多少个单元格)。下面是一些有效的代码。但它可能能够更好地优化
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);
});
});
# 1 楼答案
您可以将其收集到
List
的List
中:然后当你需要登录时: