Java 8 forEach 带索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22793006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 forEach with index
提问by Josh Stone
Is there a way to build a forEach
method in Java 8 that iterates with an index? Ideally I'd like something like this:
有没有办法forEach
在 Java 8 中构建一个使用索引迭代的方法?理想情况下,我想要这样的东西:
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++;
});
采纳答案by srborlongan
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).
生成的代码类似于使用经典的 i++ 样式的 for 循环迭代列表,除了更容易并行化(当然,假设对 params 的并发只读访问是安全的)。
回答by assylias
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
有一些解决方法,但没有干净/简短/甜蜜的方式来处理流,老实说,你可能会更好:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
或旧样式:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
回答by nosid
It works with paramsif you capture an array with one element, that holds the current index.
如果您捕获一个包含当前索引的元素的数组,则它可以与params一起使用。
int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));
The above code assumes, that the method forEachiterates through the elements in encounter order. The interface Iterablespecifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterablefrom the standard library, and changing this behaviour in the future would break backward-compatibility.
上面的代码假设forEach方法按遇到顺序遍历元素。除非另有说明,否则接口Iterable为所有类指定此行为。显然它适用于标准库中Iterable 的所有实现,并且将来更改此行为将破坏向后兼容性。
If you are working with Streamsinstead of Collections/Iterables, you should use forEachOrdered, because forEachcan be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:
如果您正在使用Streams而不是Collections/ Iterables,您应该使用forEachOrdered,因为forEach可以并发执行并且元素可以以不同的顺序出现。以下代码适用于顺序和并行流:
int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));