首页 > 解决方案 > 将元素计数和索引传递给流的 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));

我只是出于好奇而问这个,所以请不要提供任何替代方法,我已经通过使用收集器实现了它。

标签: javalambdajava-stream

解决方案


是否interactionList.size()对应totalCount

如果是,那么您可以尝试以下方法:

IntStream.range(0, interactionList.size())
         .forEachOrdered(index -> process(interactionList.get(index), index, interactionList.size()));

推荐阅读