有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在我的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) 个答案

  1. # 1 楼答案

    您可以将其收集到ListList中:

    List<List<HtmlTableCell>> columns = 
                              myTable.getRows()
                                     .stream()
                                     .map(row -> row.getCells()
                                                    .stream()
                                                    .collect(Collectors.toList())
                                     .collect(Collectors.toList());
    

    然后当你需要登录时:

    LOG.info(columns.stream()
                    .flatMap(List::stream)                    
                    .map(m -> m.asText())
                    .sorted()         //Sort the list
                    .collect(Collectors.joining("|")));