Java 8 forEach与索引 [英] Java 8 forEach with index
问题描述
forEach
方法来迭代索引?理想情况下,我想这样的事情:$ p $
params.forEach((idx,e) - > query.bind(idx ,e));
现在我可以做的最好的是:
int idx = 0;
params.forEach(e - > {
query.bind(idx,e);
idx ++;
});
等等),我假设你可以只是迭代元素的指数:
pre $ Int $ c $ IntStream.range(0,params .size())
.forEach(idx - >
query.bind(
idx,
params.get(idx)
)
)
;
结果代码类似于使用经典的i ++ - for循环迭代列表,可并行性(当然,假设对params的并发只读访问是安全的)。
Is there a way to build a forEach
method in Java 8 that iterates with an index? Ideally I'd like something like this:
params.forEach((idx, e) -> query.bind(idx, e));
The best I could do right now is:
int idx = 0;
params.forEach(e -> {
query.bind(idx, e);
idx++;
});
Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:
IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;
The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).
这篇关于Java 8 forEach与索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!