将元素数量和索引传递给流的forEach操作

huangapple go评论79阅读模式
英文:

Passing Element Count and Indices Into forEach Operation of Streams

问题

我有一个简单的Stream操作,像这样:

interactionList.stream().forEach(interaction -> process(interaction));

然后有一个process方法:

private void process(Interaction interaction) {
    doSomething(interaction);
}

我想修改我的process函数,使其可以使用元素的总数和当前处理元素的索引,就像这个更新后的版本一样:

private void process(Interaction interaction, int index, int totalCount) {
    doSomething(interaction, index, totalCount);
}

有没有一种方法可以从相同的流中收集这些参数并将它们直接传递给forEach方法的lambda表达式,而不需要使用额外的先前操作?类似于这样的写法:

interactionList.stream().forEach(interaction -> process(interaction, stream.index, stream.count));

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

英文:

I have a simple Stream operation like this:

interactionList.stream().forEach(interaction -> process(interaction));

and then a process method

private void process(Interaction interaction) {
    doSomething(interaction);
}

I want to change my process function so that it can use the total number of elements and the index of the currently processed one as in this updated version

private void process(Interaction interaction, int index, int totalCount) {
    doSomething(interaction, int index, int totalCount);
}

Is there a way to simply pass these arguments into the lambda expression of forEach method by collecting them from the same stream without using extra prior operations? Looking for something like this:

interactionList.stream().forEach(interaction -> process(interaction, stream.index, stream.count));

I am just asking this out of curiosity so please don't provide any alternative methods, I already implemented it by using collectors.

答案1

得分: 1

interactionList.size() 是否对应 totalCount

如果是的话,那么你可以尝试下面的方法:

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

Does the interactionList.size() correspond to totalCount?

If yes, then you can try the approach below:

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

huangapple
  • 本文由 发表于 2020年10月9日 16:29:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64276508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定