Java 将元素计数和索引传递到流的forEach操作中

Java 将元素计数和索引传递到流的forEach操作中,java,lambda,java-stream,Java,Lambda,Java Stream,我有一个简单的流操作,如下所示: interactionList.stream().forEach(interaction -> process(interaction)); interactionList.stream().forEach(interaction -> process(interaction, stream.index, stream.count)); 然后是一种处理方法 private void process(Interaction interaction)

我有一个简单的操作,如下所示:

interactionList.stream().forEach(interaction -> process(interaction));
interactionList.stream().forEach(interaction -> process(interaction, stream.index, stream.count));
然后是一种处理方法

private void process(Interaction interaction) {
    doSomething(interaction);
}
我想更改我的进程函数,以便它可以使用当前处理的元素总数和索引,就像在这个更新版本中一样

private void process(Interaction interaction, int index, int totalCount) {
    doSomething(interaction, int index, int totalCount);
}
有没有一种方法可以通过从相同流中收集这些参数而不使用额外的优先操作,将它们简单地传递到
forEach
方法的lambda表达式中?寻找这样的东西:

interactionList.stream().forEach(interaction -> process(interaction));
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()));

不,那样的事是不可能的。如果您想访问索引,请使用常规for循环。您所说的“不使用额外的优先操作”是什么意思?我将使用列表索引的
IntStream
。这算不算“额外的优先操作”?@Amongalen mhm很难过,但无论如何,谢谢。@Sweeper喜欢在使用流之前计算元素的数量。我想在同一个lambda操作中获取计数,只是为了清楚起见。@CanBayar的
interactionList.size()
对应于
totalCount
?在我拥有的真正代码片段中,我实际上没有列表,但直接拥有流。但既然我在问题中给出了清单,谢谢哈哈。:)