英文:
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()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论