gpt4 book ai didi

java - 如何为要并行处理的 java 列表中的每个项目添加索引

转载 作者:行者123 更新时间:2023-12-01 19:50:18 24 4
gpt4 key购买 nike

我有一个 Rec 列表,我想通过调用某个方法 foo() 并行处理它们。

foo() 可能会将某些 Rec 标记为错误,最后所有错误记录均按其索引位置报告(例如“rec 12 无效”) ”)。
所以我想要么将每个 Rec 的索引位置传递给 foo(),要么在调用 foo 之前将索引设置到每个 Rec 中。
我尝试做的(如下所示)是首先按顺序将索引设置为每个 Rec,然后并行调用每个 foo 。有更好的方法吗?

List<Rec> recs;
class Rec {
private int recordIndex;
public void setRecordIndex( int index) { recordIndex = index; }
//more memebers and getter to the above...
}

//somewhere in the code
int index = 0;
recs.stream().forEach(rec -> rec.setRecordIndex(index++));
//the compiler complains about the index++ above, says it should be final
rec.parallelStream().forEach(rec -> foo(ProgressInfo, rec));

总体上有更好的方法吗?如果没有,有没有办法修复编译错误并仍然使用流? (而不是循环)

最佳答案

这可以通过 IntStream 来完成,我也建议仅使用一个 Stream:

IntStream.range(0, recs.size())
.mapToObj(i -> {
Rec rec = recs.get(i);
rec.setRecordIndex(i);
return rec;
})
.parallel()
.forEach(rec -> foo(ProgressInfo, rec));

尽管不鼓励修改 streams 中的状态,所以最好返回一个 mapToObj 内的 index新对象。例如。像这样的东西:

.mapToObj(i -> {
Rec copy = new Rec(recs.get(i)); // copy constructor
copy.setRecordIndex(i);
return copy;
})
<小时/>

取决于您使用的 List 实现(使用索引访问时,ArrayList 的性能优于 LinkedList)>),您还可以使用以下代码片段。但使用peek在生产代码中有点争议。

IntStream.range(0, recs.size())
.peek(i -> recs.get(i).setRecordIndex(i))
.parallel()
.forEach(i -> foo(ProgressInfo, recs.get(i));

关于java - 如何为要并行处理的 java 列表中的每个项目添加索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51511811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com