java - 将元素计数和索引传递给流的 forEach 操作
问题描述
我有一个像这样的简单流操作:
interactionList.stream().forEach(interaction -> process(interaction));
然后是一个处理方法
private void process(Interaction interaction) {
doSomething(interaction);
}
我想更改我的流程功能,以便它可以使用元素总数和当前处理的元素的索引,就像在这个更新版本中一样
private void process(Interaction interaction, int index, int totalCount) {
doSomething(interaction, int index, int totalCount);
}
有没有办法通过从同一个流中收集它们而不使用额外的先前操作来简单地将这些参数传递到方法的lambda 表达式中?寻找这样的东西:forEach
interactionList.stream().forEach(interaction -> process(interaction, stream.index, stream.count));
我只是出于好奇而问这个,所以请不要提供任何替代方法,我已经通过使用收集器实现了它。
解决方案
是否interactionList.size()
对应totalCount
?
如果是,那么您可以尝试以下方法:
IntStream.range(0, interactionList.size())
.forEachOrdered(index -> process(interactionList.get(index), index, interactionList.size()));
推荐阅读
- laravel - Laravel Spark 用户字段
- python - python中的修补类不执行模拟对象
- c# - 如何在 Xamarin.Forms UWP 中隐藏默认工具栏按钮(三个点)
- amazon-web-services - 带有 --include 和 --exculde 的 aws s3 cp 不会复制任何内容
- haskell - 用于二叉树的 Haskell 插入函数
- c++ - 我如何知道作为 r 值传递的对象是否会被移动?
- r - 用 R 数据框列中的 NA 替换字符串
- php - 在 Twig 和 PHP 中搜索选定的值
- java - Visual Studio Code:格式化 Java 方法链
- grpc - gRpc 双向流