首页 > 解决方案 > 在我的 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);
        });
    });

标签: javajava-streamhtmlunit

解决方案


您可以将其作为单个流加入的一部分:

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("|"));

推荐阅读