如何计算流过滤器的匹配项?我正在尝试将以下代码重构为 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/