java - 如何计算流过滤器上的匹配项?

标签 java java-8 java-stream

如何计算流过滤器的匹配项?我正在尝试将以下代码重构为 java8 stream:

//java7
int i = 0;
for (Node node : response.getNodes()) {
    Integer id = node.getId();
    if (id != null) {
        node.setContent("This is the id: " + id);
        i++;
    }
}

//java8
response.getNodes().stream()
    .filter(node -> node.getId() != null)
    .forEach(node -> node.setValue("This is the id: " + node.getId()));

我现在如何获取已应用的已过滤元素的数量? 附带问题:在旧代码中,我可以多次重复使用 Integer id。如何使用流实现同样的效果?

最佳答案

由于 setValue 是一个副作用函数,您可以使用 peek:

long i = response.getNodes()
                 .stream()
                 .filter(node -> node.getId() != null)
                 .peek(node -> node.setValue("This is the id: " + node.getId()))
                 .count();

我不喜欢这种方法,因为 peak 用于调试目的(这可以解决问题)。请注意,在 Java 9 中,如果 count() 可以直接从源计算计数,则它可能无法执行流管道(我认为这里不是这种情况,因为您应用了过滤,但最好记住这一点)。

Sidequestion: in the old code I can reuse the Integer id multiple times. How can I achieve the same with streams?

这取决于您的用例,因为 API 没有元组,您最好的机会是创建一个类,比如说 Tuple2,这样您就可以将每个节点映射到一个新的元组并重用该 ID。

类似于:

.stream().map(node -> new Tuple2<>(node, node.getId()).moreStreamOps(...);
                                                      ^
                                                      |
                 at that point you have a Stream<Tuple2<Node, Integer>> 
                 from which you can grab the id with Tuple2#getSecond

在您的情况下,如果您留在节点流中,则可以随时使用 getId() 获取 ID。

关于java - 如何计算流过滤器上的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29260288/

相关文章:

java - Struts2 验证 - 验证失败时重新填充子项

java - Spring Boot 类 Size 未找到 @Size(min=1,max=18)

java - 在java中使用泛型为集合到数组转换分配数组的必要性

java - 参数返回 void 的可调用/可运行/函数?

java - 如何为 lombok 编写具有单一注释的集合数据类型的自定义 build() 函数?

java - 带数组构造函数的引用方法

java - 如何在 Java 中对通配符列表进行排序

java - 而无限循环

scala - Scala中有没有类似Java Stream的 "peek"操作的东西?

java - 基于 2 个对象对列表中的元素进行分组,如果它们具有相同的值,则仅显示该元素一次,并显示计数