java - 在我的 java 8 流中查找表中的每一列
问题描述
我HtmlUnit
用来获取HtmlTable
. 我正在尝试获取每列的单元格列表。
到目前为止,在我尝试过的代码中,我可以找到第一列。如何遍历每一列并在其中运行一些代码?
我想确保它们都按字母顺序排序,但我只需要弄清楚该代码的放置位置。
编辑:我找到了答案。我想我的问题措辞错误。我需要获取每一列并将它们放入自己的集合中。在原始示例中,我只显示了 column1。但我需要每列(基于每行中有多少个单元格)。下面是一些有效的代码。但它可能能够更好地优化。
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);
});
});
解决方案
您可以将其作为单个流加入的一部分:
webClient.getPage("http://localhost:8080/myUrl")
.getHtmlElementById("myTable")
.getRows()
.stream()
.map(row -> row.getCells().stream().findFirst().get().asText())
.sort((o1, o2) -> o1.compareTo(o2)) // make alphabetical
.collect(Collectors.joining("|"));
推荐阅读
- python - 极高的损失和一致的验证准确性
- c# - 为什么我的网络表单直到 OnSaveStateComplete 才检测到我的列表框的内容?我怎样才能更早地检测到它们?
- dask - dask-gateway (helm 部署):如何配置自定义身份验证器?
- javascript - 如何实现可调整大小和自动隐藏侧边菜单
- nfc - ACR122U NFC 读卡器在卡为只读时无法正确读取 ISO14443 卡
- c++ - 如果分隔符是输入范围的最后一个元素,为什么 views::split 会忽略分隔符后的空子范围?
- html - 如何在页面上的其他内容下正确定位 HTML 元素?
- informatica - Informatica Cloud 中的文件侦听器
- php - 我将如何只让用户类型“管理员”访问我的 PHP 项目中的某些页面?
- python - 如何在 Django 视图页面中显示外键数据?